Entity Framework 4.1 Code First Foreign Key Id's

前端 未结 3 1340
感情败类
感情败类 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:08

    You must specify the many-end of the association explicitely:

    modelBuilder.Entity()
        .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.

提交回复
热议问题