在HasOptional()中映射外键。在实体框架中WithOptionalDependent()关系6 [英] Mapping foreign key in HasOptional().WithOptionalDependent() relation in Entity Framework 6
问题描述
我在Entity Framework 6.1.3中有以下数据模型:
I have the following data-model in 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);
}
}
当我启动这段代码时,我得到了正确的表结构我的目标是:
When I launch this code, I get exactly the right table structure I am aiming for:
dbo.Contacts
Id (PK)
Student_Id (FK, NULL, CASCADE ON DELETE)
dbo.Students
Id (PK)
但是,现在我想在联系人
实体中添加 Student_Id
属性。所以我可以阅读 Student_Id
,而无需通过 .Student.Id
导航加入其他表。
However, now I would like to add the Student_Id
property to be available in the Contact
entity. So I can read the Student_Id
without needing to join the other table through .Student.Id
navigation.
如果我将属性添加到联系人
实体中,我可以使用两列 Student_Id
和 Student_Id1
,或者我最后会出现一条错误消息,说类型中的每个属性名称必须是唯一的。
。
If I add the property to the Contact
entity, I end up either with two columns Student_Id
and Student_Id1
, or I end up with an error message saying Each property name in a type must be unique.
.
列已经在数据库中,我需要的只是在实体中拥有它,为什么这么麻烦?有没有一个解决方案?
The column is already in the database, all I need is to have it in the entity as well, why is it so much trouble? Is there a solution?
推荐答案
我设法在询问GitHub 。
这篇关于在HasOptional()中映射外键。在实体框架中WithOptionalDependent()关系6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!