Creating Relational Tables in Entity Framework - asp.net

I am trying to build a pretty extensive database heavy web application and doing so with little experience. What I am trying to figure out is creating a relational table in entity framework through scaffolding.
It seems I have accidentally done this already with these two models, but I have no idea how it happened:
namespace FlavorPing.Models
{
public class MenuItem
{
[Key]
public int MenuItemID { get; set; }
public string ItemName { get; set; }
public string Description { get; set; }
//Category
//May need to put this back and add to controllers and views.
//[ForeignKey("Merchant")]
//public int MerchantID { get; set; }
public virtual Merchant Merchant { get; set; }
public ICollection<Follower> Followers { get; set; }
}
}
public class Merchant
{
//Meant to inherit identity.
[ForeignKey("ApplicationUserId")]
public string ApplicationUserId { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
[Key]
public int MerchantID { get; set; }
[Required]
[Display(Name = "Business Name")]
public string MerchantName { get; set; }
[Required]
[Display(Name = "Email")]
[DataType(DataType.EmailAddress)]
public string email { get; set; }
//need to create formatting here.
[Required]
[Display(Name = "Web Site Link")]
public string website { get; set; }
public int MenuItemID { get; set; }
public virtual List<MenuItem> MenuItems { get; set; }
public virtual MerchantDetails MerchantDetails { get; set; }
}
The above models have their own dedicated tables, but a second table MenuItemFollowers was created with the MenuItemID and FollowerID as columuns, which I want, but I have no idea how I did this and need to know so I could add another ID to this table.

Related

When creating a one-to-one relationship in an entity it throws an error The navigation property 'StudentModel' was not found on the dependent type

I want to create one to one relation between tables. My table is
public class StudentModel
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime DateOfBirth { get; set; }
[Required, Display(Name="Department Name")]
public int DeptId { get; set; }
//navigration proprty
[ForeignKey("DeptId")]
public virtual DepartmentModels Department { get; set; }
public virtual StudentRegistrationModels StudentRegistration { get; set; }
}
and my other table is
public class StudentRegistrationModels
{
[Key]
public int StudentId { get; set; }
[Required]
public int CourseId { get; set; }
[Required]
public DateTime EnrollDate { get; set; }
public bool IsPaymentComplete { get; set; }
//navigration proprty
[ForeignKey("StudentId")]
public virtual StudentModel Student { get; set; }
[ForeignKey("CourseId")]
public virtual CourseModels Course { get; set; }
//oneToOneStudentRegistration
}
But when I make migration it throws an error:
Unable to determine the principal end of an association between the types 'StudentManagementSystem.Models.StudentModel' and 'StudentManagementSystem.Models.StudentRegistrationModels'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
Why is this occurring?
I believe the issue is that you have a single StudentRegistrationModel instance in your StudentModel, where the StudentRegistrationModel looks to be more of a Many-to-Many structure. Can a single student only be registered to a single course? If that were the case it would make more sense for StudentModel to just have a CourseModel reference. Since a Student probably has multiple courses, it would probably make more sense for StudentModel to have:
public virtual ICollection<StudentRegistrationModels> StudentRegistration { get; set; } = new List<StudentRegistrationModels>();
Then ensuring that your model configuration maps out the relationship. This can be done with an attribute, as part of the DbContext OnModelCreating, or using an EntityTypeConfiguration. With Attributes:
[InverseProperty("Student")] // Tells EF this collection corresponds to the Student on the StudentRegistrationModel.
public virtual ICollection<StudentRegistrationModels> StudentRegistration { get; set; } = new List<StudentRegistrationModels>();
Maybe try to add [Key] annotation to Id field in StudentModel.
using System.ComponentModel.DataAnnotations;
public class StudentModel
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime DateOfBirth { get; set; }
[Required, Display(Name="Department Name")]
public int DeptId { get; set; }
//navigration proprty
[ForeignKey("DeptId")]
public virtual DepartmentModels Department { get; set; }
public virtual StudentRegistrationModels StudentRegistration { get; set; }
}
or if it won't work try map relationship in OnModelCreating in your data context.

Multi-Level One to Many in ASP MVC5

I am working on a small project, where I have multi-level one-to-many model. But for some reason, the EF doesn't seem to understand this relationship and I receive an error when I create the MVC controller with EF.
Here are my model classes:
public class BusinessDomain
{
[Key]
public int BusinessDomainID { get; set; }
[Display(Name = "Business Domain Name")]
public string DomainName { get; set; }
[Display(Name = "Domain Manager Name")]
public string DomainManager { get; set; }
public virtual ICollection<BusinessProcess> BusinessProcesses { get; set; }
}
public class BusinessProcess
{
public int BusinessProcessID { get; set; }
[Display(Name = "Business Processs Name")]
public string ProcessName { get; set; }
[Display(Name = "Business Process Owner Name")]
public string ProcessOwner { get; set; }
public virtual ICollection<BusinessSubProcess> BusinessSubProcesses { get; set; }
public int BusinessDomainID { get; set; }
public virtual BusinessDomain BusinessDomain { get; set; }
}
public class BusinessSubProcess
{
public int BusinessSubProcessId { get; set; }
public string SubProcessName { get; set; }
public string SubProcessOwnerName { get; set; }
public int BusinessProcessID { get; set; }
public virtual BusinessProcess BusinessProcess { get; set; }
}
When I create a EF controller, I get following error: Dependent role refers to the key properties, the upper bound of the multiplicity of the Dependent role must be 1.
If I keep only two models (BusinessLine and BusinessProcess) it seems to work. I begin to wonder if ASP MVC doesnt support multilevel of one to many models?
Please tell me what am I doing wrong?
Thanks in advance!
The only difference that I see is that you do not include a reference to the BusinessLine object in the BusinessProcess class. You should include that and also mark it as a foreign key.
Also, you marked the BusinessSubprocessID as a foreign key to the BusinessProcess, which I believe is a mistake since you also hold a BusinessProcessID in your class.
As a side note, do you need the BusinessLineID in your subprocess class, since you can easily access it through its parent?
public class BusinessLine
{
[Key]
public int BusinessLineID { get; set; }
[Display(Name = "Business Domain Name")]
public string DomainName { get; set; }
[Display(Name = "Domain Manager Name")]
public string DomainManager { get; set; }
public virtual ICollection<BusinessProcess> BusinessProcesses { get; set; }
}
public class BusinessProcess
{
[Key]
public int BusinessProcessID { get; set; }
[Display(Name = "Business Processs Name")]
public string ProcessName { get; set; }
[Display(Name = "Business Process Owner Name")]
public string ProcessOwner { get; set; }
public virtual ICollection<BusinessSubProcess> BusinessSubProcesses { get; set; }
public int BusinessLineID { get; set; }
[ForeignKey("BusinessLineID")]
public virtual BusinessLine BusinessLine { get; set; }
}
public class BusinessSubProcess
{
[Key]
public int BusinessSubProcessId { get; set; }
public string SubProcessName { get; set; }
public string SubProcessOwnerName { get; set; }
public DateTime Created { get; set; }
public DateTime LastChange { get; set; }
public int BusinessProcessID { get; set; }
[ForeignKey("BusinessProcessID")]
public virtual BusinessProcess BusinessProcess { get; set; }
}

Online Shop - Create an order with multiple products MVC .net

So I am building an online shop using Code-First MVC
So I created this model classes for now (don't take the types of the attributes too serious for now):
Products (Produto):
public Produto()
{
ListaProdutoEncomenda = new HashSet<Produto_Encomenda>();
}
public int ProdutoID { get; set; }
[Required]
[StringLength(50)]
public string Nome { get; set; }
[Required]
public double Preco { get; set; }
[Required]
public double Peso { get; set; }
[Required]
[StringLength(255)]
public string Descricao { get; set; }
[Required]
public double IVA { get; set; }
public string Imagem { get; set; }
public DateTime UltimaAtualizacao { get; set; }
public int Stock { get; set; }
public int CategoriaID {get;set;}
public virtual ICollection<Produto_Encomenda> ListaProdutoEncomenda { get; set; }
}
Encomenda (Order):
public class Encomenda
{
public Encomenda()
{
ListaProdutoEncomenda = new HashSet<Produto_Encomenda>();
}
[Key]
public int IDEncomenda { get; set; }
[Required]
public DateTime DataSubmissao { get; set; }
[Required]
public DateTime DataEnvio { get; set; }
[Required]
public int EstadoEnvioID { get; set; }
[StringLength(50)]
public string NomeDestino { get; set; }
[Required]
public int TipoExpedicaoID { get; set; }
[Required]
public int RegiaoDestinoID { get; set; }
[StringLength(50)]
public string MoradaDestino { get; set; }
[StringLength(50)]
public string CodPostalDestino { get; set; }
[Required]
[StringLength(50)]
public string MoradaFaturacao { get; set; }
[Required]
[StringLength(50)]
public string CodPostalFaturacao { get; set; }
public virtual ICollection<Produto_Encomenda> ListaProdutoEncomenda { get; set; }
}
And the connection table between the produtos (Products) and Encomenda (Order)
public class Produto_Encomenda
{
[Key]
public int IDProduto_Encomenda { get; set; }
[Required]
public string NomeProduto { get; set; }
[Required]
public int Quantidade { get; set; }
[Required]
public float preco { get; set; }
[Required]
public float IVA { get; set; }
public virtual Encomenda Encomenda { get; set; }
public virtual Produto Produto { get; set; }
[ForeignKey("Encomenda")]
public int IDEncomendaFK { get; set; }
[ForeignKey("Produto")]
public int IDProdutoFK { get; set; }
}
So my question is..
Let's pretend that a costumer buys 2 or 3 products or more.
How can I store all this products in a single line of an order?
Cheers and thanks a lot in advance for the time spent reading.
I'm not sure what you mean by "a single line of an order". Each product is a separate line item, and your entities already model this through the many-to-many relationship.
However, in general this setup is a very bad idea. Your order should not be directly related to products. Instead, your order should simply have an order item, and you'll create those order items based on the products that were sold. The reason for this is that products are very likely to change. If a product is removed because it's no longer available, for example, that doesn't negate the fact that it was previously sold in an order. However, in order for referential integrity to be maintained, any orders sold with that product would have to also have their relationship with that product removed. By having an entirely separate entity, i.e. order item, products can come and go, while the already created orders remain unaffected.
I guess you are looking to make a viewmodel
Create a class that contains Products and Encomenda class as property -
Model -
public class MyViewModel
{
public Produto Pinst{get;set;}
public Encomenda Einst{get;set;}
}
Controller or method-
public void SomeMethod()
{
List<MyViewModel> lst = new List<MyViewModel>();
//Now suppose
foreach(var items in listThatGetCreatedWithBuyerproductInfo)
{
MyViewModel obj = new MyViewModel ();
obj.Pinst = new Produto();
obj.Einst = new Encomenda();
//Here goes your properties from item in respected class instances
obj.Pinst.Nome = items.Nome;
obj.Einst.DataSubmissao = items.DataSubmissao;
//when you are done loading add obj to list
lst.Add(obj);
}
}
Hope it Helps if it does not tell me !!

Mapping existing database with code first approch

I have implemented asp .net application without Code first approach. now i want to build different system with existing database and code first.
public class EmployeeEntity
{
public int Id { get; set; }
public string ResourceCode { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public int Gender { get; set; }
public int Status { get; set; }
public string NIC { get; set; }
}
now i want to add code first entities.
[Table("ExternalApplicantEntity")]
public class ExternalApplicantEntity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ApplicantID { get; set; }
//[ForeignKey("EmployeeEntity")]
//public int Created_By { get; set; }
//public virtual EmployeeEntity EmployeeEntity { get; set; }
public string NIC { get; set; }
public string Mobile { get; set; }
public string Institute { get; set; }
how i combine these codes?

Unable to add second self Referencing FK to model, causes Unable to determine the principal end error

First off, I know there are a lot of posts about the Unable to determine the principal end of an association between the types error but ever single one I see does not match my issue, if I missed one sorry about that.
I have built an Entity that will end up referencing it's self twice and when I put the code in for the first self reference it works fine, as soon as ad the code for the second it breaks. Doing some testing I have found that if I use either of the self references by them self everything works fine, it is only when I add the second self reference that it breaks. The code I am using for the self references is:
[ForeignKey("ManagerID")]
public User Manager { get; set; }
//Auditing Fields
public DateTime DateCreated { get; set; }
public int? UpdatedByUserID { get; set; }
public DateTime? DateUpdated { get; set; }
public DateTime LastAutoUpdate { get; set; }
[ForeignKey("UpdatedByUserID")]
public User UpdatedByUser { get; set; }
The full entity code block is:
public class User
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public int ADPFileNumber { get; set; }
[Required]
public string ADUserName { get; set; }
public int AirCardCheckInLateCount { get; set; }
[Required]
public string Email { get; set; }
public DateTime? EndDate { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
public int ManagerID { get; set; }
public string MobilePhone { get; set; }
[Required]
public string Office { get; set; }
[Required]
public string Phone { get; set; }
public decimal PTO { get; set; }
public DateTime StartDate { get; set; }
public int VehicleCheckInLateCount { get; set; }
public int WexCardDriverID { get; set; }
[ForeignKey("ManagerID")]
public User Manager { get; set; }
//Auditing Fields
public DateTime DateCreated { get; set; }
public int? UpdatedByUserID { get; set; }
public DateTime? DateUpdated { get; set; }
public DateTime LastAutoUpdate { get; set; }
[ForeignKey("UpdatedByUserID")]
public User UpdatedByUser { get; set; }
}
What am I missing that cause the second self reference to break?
You have to indicate the principal end of both associations explicitly. You can do that with the class you had originally, without inverse collection properties:
modelBuilder.Entity<User>()
.HasOptional(u => u.Manager)
.WithMany()
.HasForeignKey(u => u.ManagerID);
modelBuilder.Entity<User>()
.HasOptional(u => u.UpdatedByUser)
.WithMany()
.HasForeignKey(u => u.UpdatedByUserID);
Note that ManagerID should be an int? as well. You can't create any User if it requires another user to preexist. That's a chicken-and-egg problem.
As mentionned in Multiple self-referencing relationships in Entity Framework, you seem to be missing the other part of the relationship.
i.e.
[InverseProperty("Manager")]
public virtual ICollection<User> ManagedUsers {get;set;}
[InverseProperty("UpdatedByUser")]
public virtual ICollection<User> UpdatedUsers {get;set;}
EDIT: based on #Gert Arnold's answer you should indeed add the [InverseProperty] attribute

Resources