实体框架 - 代码优先 - 数据注释 - 不必要的外键列

时间:2016-03-07 08:29:59

标签: c# asp.net asp.net-mvc entity-framework entity-framework-6

Entity Framework在我的AccountCompanyRole表中创建了两个不必要的列。

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);
    }

DB中的结果

Result in DB

如您所见,EF在AccountCompanyRoles中添加了两个额外的外键,即使我在数据注释中指定了主键和外键。

问题

  1. 如何阻止它创建AccountCompany_AccountID和AccountCompany_CompanyID?

  2. 这是我追求的最佳结构吗?我应该使用一个主键并将IsUnique索引放在AccountID和CompanyID上吗?这可能会解决我的问题..

2 个答案:

答案 0 :(得分:3)

  

如何阻止它创建AccountCompany_AccountID和AccountCompany_CompanyID?

首先,从ForeignKeyCompanyID中删除RoleID属性。

然后将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);
  

这是我追求的最佳结构吗?我应该使用一个主键并将IsUnique索引放在AccountID和CompanyID上吗?这可能会解决我的问题..

IMO都是有效的方法,使用最适合您需求的方法。

答案 1 :(得分:1)

您必须在流利关系中指定外键,如下所示:

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});

修改 为AccountCompany添加了流畅的配置