我在 Entity Framework 6.1.3 中有以下数据模型:
using System.Data.Entity;
public class Student
{
public int Id { get; set; }
public virtual Contact Contact { get; set; }
}
public class Contact
{
public int Id { get; set; }
public virtual Student Student { get; set; }
}
public class MyContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder builder)
{
builder.Entity<Contact>()
.HasOptional(x => x.Student)
.WithOptionalDependent(x => x.Contact)
.WillCascadeOnDelete(true);
}
}
public static class Program
{
private static void Main()
{
Database.SetInitializer(new DropCreateDatabaseAlways<MyContext>());
using (var context = new MyContext())
context.Database.Initialize(force: true);
}
}
当我启动这段代码时,我得到了我想要的正确表结构:
dbo.Contacts
Id (PK)
Student_Id (FK, NULL, CASCADE ON DELETE)
dbo.Students
Id (PK)
但是,现在我想添加 Student_Id
属性以在 Contact
实体中可用。所以我可以读取 Student_Id
而无需通过 .Student.Id
导航加入其他表。
如果我将属性添加到 Contact
实体,我最终会得到两列 Student_Id
和 Student_Id1
,或者我最终得到一条错误消息,指出 类型中的每个属性名称必须是唯一的。
。
该列已经在数据库中,我只需要在实体中也有它,为什么这么麻烦?有解决办法吗?
最佳答案
在 asking on GitHub 之后,我设法得到了 Entity Framework Program Manager 的回复。 .
Unfortunately this is a limitation of EF6. You can not have a foreign key property in a one-to-one relationship, unless it is also the primary key property. This is essentially because EF6 doesn't support alternate keys/unique indexes, so you can't enforce that a non-primary key property is unique. The fact that you can do it when the foreign key property isn't in the entity is a bit of a quirk... but obviously not something we would remove 😄.
BTW alternate keys (and therefore this scenario) is supported in EF Core.
——罗文·米勒@ https://github.com/aspnet/EntityFramework6/issues/159#issuecomment-274889438
关于c# - 在 Entity Framework 6 中映射 HasOptional().WithOptionalDependent() 关系中的外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32313842/