我在 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.
.
该列已经在数据库中,我只需要在实体中也有它,为什么这么麻烦?有解决办法吗?