Entity Framework 在我的 AccountCompanyRole 表中创建了两个不必要的列。
账户公司
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);
}
数据库中的结果
如您所见,EF 在 AccountCompanyRoles 中添加了两个额外的外键,即使我在数据注释中指定了主键和外键。
问题
如何阻止它创建 AccountCompany_AccountID 和 AccountCompany_CompanyID?
这是我想要的最佳结构吗?我是否应该改用一个主键并将 IsUnique 索引放在 AccountID 和 CompanyID 上?这可能会解决我的问题..
最佳答案
How do I prevent it from creating AccountCompany_AccountID and AccountCompany_CompanyID?
首先,从 CompanyID
和 RoleID
中删除 ForeignKey
属性。
然后将 ForeignKey
属性放在您的 AccountCompany
成员上,如下所示:
public class AccountCompanyRole
{
[Key, Column(Order = 0)]
public int AccountID { get; set; }
[Key, Column(Order = 1)]
public int CompanyID { get; set; }
[Key, Column(Order = 2), ForeignKey("Role")]
public int RoleID { get; set; }
[ForeignKey("AccountID, CompanyID")]
public virtual AccountCompany AccountCompany { get; set; }
public virtual Role Role { get; set; }
}
或者像这样使用流畅的配置:
modelBuilder.Entity<AccountCompanyRole>()
.HasRequired(r => r.AccountCompany)
.WithMany(c => c.AccountCompanyRoles)
.HasForeignKey(r => new { r.AccountID, r.CompanyID })
.WillCascadeOnDelete(false);
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..
IMO 两者都是有效的方法,请使用更适合您需求的方法。
关于c# - Entity Framework - 代码优先 - 数据注释 - 不必要的外键列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35839240/