简体   繁体   English

实体框架4.1代码第一外键ID

[英]Entity Framework 4.1 Code First Foreign Key Id's

I have two entities referenced one to many. 我有两个实体引用了一对多。 When entity framework created the table it creates two foreign keys, one for the key I have specified with the fluent interface and the other for the ICollection. 当实体框架创建表时,它会创建两个外键,一个用于我用Fluent接口指定的键,另一个用于ICollection。 How do I get rid of the duplicate foreign key? 如何摆脱重复的外键?

public class Person
{
    public long RecordId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string Username { get; set; }

    public long DepartmentId { get; set; }
    public virtual Department Department { get; set; }
}

public class Department
{
    public long RecordId { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Person> People { get; set; }
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Person>()
        .HasRequired(p => p.Department)
        .WithMany()
        .HasForeignKey(p => p.DepartmentId)
        .WillCascadeOnDelete(false);
}

Thanks! 谢谢!

You must specify the many-end of the association explicitely: 您必须明确指定关联的多端:

modelBuilder.Entity<Person>()
    .HasRequired(p => p.Department)
    .WithMany(d => d.People)
    .HasForeignKey(p => p.DepartmentId)
    .WillCascadeOnDelete(false);

Otherwise EF will assume that there are two associations: One which is not exposed in Department with the foreign key DepartmentId and navigation property Department in the Person class as you have defined in the Fluent code - and another association which belongs to the exposed navigation property People but with another not exposed end in Person and a foreign key automatically created by EF. 否则,EF将假定有两个关联:一个没有在Department暴露的Department ,如在Fluent代码中定义的Person类中的外键DepartmentId和导航属性Department - 以及另一个属于暴露导航属性的关联People但是另一个没有暴露的PersonPerson和EF自动创建的外键。 That's the other key you see in the database. 这是您在数据库中看到的另一个键。

The default Code First conventions detect your DepartmentId foreign key, since it is, well, conventional. 默认的Code First约定检测您的DepartmentId外键,因为它是传统的。 I think you should remove the Fluent definition: 我认为你应该删除Fluent定义:

modelBuilder.Entity<Person>()
    .HasRequired(p => p.Department)
    .WithMany()
    .WillCascadeOnDelete(false);

best thing is to remove departmentid property from Person class and add the following statement. 最好的方法是从Person类中删除departmentid属性并添加以下语句。 MapKey will create foreign key column with the name you specify MapKey将使用您指定的名称创建外键列

 modelBuilder.Entity<Person>().HasRequired(p =>  p.Department)
    .WithMany().Map(x=>x.MapKey("DepartmentId"))
    .WillCascadeOnDelete(false);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM