【发布时间】:2015-11-25 15:23:22
【问题描述】:
我在 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,或者我会得到一条错误消息,指出Each property name in a type must be unique.。
该列已经在数据库中,我只需要在实体中也有它,为什么这么麻烦?有解决办法吗?
【问题讨论】:
-
您可以通过将 FK 字段添加到您的模型来防止 EF 隐式创建 FK 字段: public int Student_Id { get;放;然后用注释或流利的方式指出这是导航属性的外键。
-
@SteveGreene:我试图这样做,但是,正如我在问题中所说,EF 不允许我这样做。它要么创建两列,要么抱怨属性名称的唯一性。我尝试将字段添加到模型中,我什至尝试使用 MapKey 函数配置关系,但没有成功。
-
对,你需要告诉EF如何与HasForeignKey或MapKey进行关联。 patrickdesjardins.com/blog/…
-
@SteveGreene:感谢您的帮助。 HasForeignKey 的问题在于它仅在
WithMany关系中可用。当我尝试使用 MapKey 时,我会得到两列或者我提到的错误。
标签: c# entity-framework fluent-entity-framework