c# - 在 Entity Framework 6 中映射 HasOptional().WithOptionalDependent() 关系中的外键

标签 c# entity-framework fluent-entity-framework

我在 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_IdStudent_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/

相关文章:

c# - 在 LINQ 中查询子集合

c# - 如何评估数组类型声明 'new int[10][]'?

c# - 为 .NET ala Boost.Functional/Hash 创建 'good' 哈希码

c# - DBContext 自定义验证

database - Entity Framework : how to create double relationship (1-1 and many-1) with same objects

entity-framework - 是否有使用 Fluent API 的 C# EF6 DbContext 生成器?

c# - 使用 HasForeignKey 一对零或一

c# - 在 Unity 2D 中翻转 2D Sprite 动画

java - JPA:消息+通知数据库架构

c# - 'OR'如何在LINQ的几个where条件之间进行操作