Entity Framework 4.1 Code First Foreign Key Id's

前端 未结 3 1329
感情败类
感情败类 2021-01-31 05:09

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 t

相关标签:
3条回答
  • 2021-01-31 06:02

    The default Code First conventions detect your DepartmentId foreign key, since it is, well, conventional. I think you should remove the Fluent definition:

    modelBuilder.Entity<Person>()
        .HasRequired(p => p.Department)
        .WithMany()
        .WillCascadeOnDelete(false);
    
    0 讨论(0)
  • 2021-01-31 06:04

    best thing is to remove departmentid property from Person class and add the following statement. MapKey will create foreign key column with the name you specify

     modelBuilder.Entity<Person>().HasRequired(p =>  p.Department)
        .WithMany().Map(x=>x.MapKey("DepartmentId"))
        .WillCascadeOnDelete(false);
    
    0 讨论(0)
  • 2021-01-31 06:08

    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. That's the other key you see in the database.

    0 讨论(0)
提交回复
热议问题