Entity Framework is creating two unnecessary columns in my AccountCompanyRole table.
AccountCompany
public class AccountCompany
{
[Key, Column(Order = 0), ForeignKey("Account")]
public int AccountID { get; set; }
[Key, Column(Order = 1), ForeignKey("Company")]
public int CompanyID { get; set; }
public virtual Account Account { get; set; }
public virtual Company Company { get; set; }
public virtual ICollection<AccountCompanyRole> AccountCompanyRoles { get; set; }
}
AccountCompanyRoles
public class AccountCompanyRole
{
[Key, Column(Order = 0), ForeignKey("AccountCompany")]
public int AccountID { get; set; }
[Key, Column(Order = 1), ForeignKey("AccountCompany")]
public int CompanyID { get; set; }
[Key, Column(Order = 2), ForeignKey("Role")]
public int RoleID { get; set; }
public virtual AccountCompany AccountCompany { get; set; }
public virtual Role Role { get; set; }
}
OnModelCreating
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<AccountCompanyRole>()
.HasRequired(p => p.AccountCompany)
.WithMany()
.WillCascadeOnDelete(false);
base.OnModelCreating(modelBuilder);
}
Result in DB
As you can see, EF has added two extra foreign keys in AccountCompanyRoles even tho I specified primary key and foreign key in Data Annotations.
Questions
How do I prevent it from creating AccountCompany_AccountID and AccountCompany_CompanyID?
Is this the best structure for what I am after? Should I instead use one primarykey and put IsUnique index on AccountID and CompanyID? This would probably solve my problem..
You have to specify the foreign keys in your fluent relationship like this:
modelBuilder.Entity<AccountCompanyRole>()
.HasRequired(p => p.AccountCompany)
.WithMany().HasForeignKey(d => new { d.AccountID, d.CompanyID })
.WillCascadeOnDelete(false);
modelBuilder.Entity<AccountCompany>()
.HasMany(c => c.AccountCompanyRoles)
.WithRequired(d => d.AccountCompany)
.HasForeignKey(e => new {e.AccountID, e.CompanyID});
Edit: Added fluent config for AccountCompany
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments