实体框架 4.1 代码优先外键 ID
我有两个一对多引用的实体。当实体框架创建表时,它会创建两个外键,一个用于我使用 Fluent 接口指定的键,另一个用于 ICollection。如何删除重复的外键?
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);
}
谢谢!
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. 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您必须显式指定关联的多端:
否则 EF 将假定有两个关联: 一个未在
Department
中通过外键DepartmentId
和导航公开您在 Fluent 代码中定义的Person
类中的属性Department
- 以及属于公开的导航属性People
的另一个关联,但与另一个关联未公开Person
中的结尾以及 EF 自动创建的外键。这是您在数据库中看到的另一个键。You must specify the many-end of the association explicitely:
Otherwise EF will assume that there are two associations: One which is not exposed in
Department
with the foreign keyDepartmentId
and navigation propertyDepartment
in thePerson
class as you have defined in the Fluent code - and another association which belongs to the exposed navigation propertyPeople
but with another not exposed end inPerson
and a foreign key automatically created by EF. That's the other key you see in the database.默认的 Code First 约定会检测您的 DepartmentId 外键,因为它是常规的。我认为你应该删除 Fluent 定义:
The default Code First conventions detect your DepartmentId foreign key, since it is, well, conventional. I think you should remove the Fluent definition:
最好的办法是从 Person 类中删除 Departmentid 属性并添加以下语句。 MapKey 将使用您指定的名称创建外键列
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