【问题标题】:EF inheritance and primary keysEF 继承和主键
【发布时间】:2013-05-16 19:11:47
【问题描述】:

我不确定这在 EF 中是否可行,但我正在创建一堆类并试图让 EF 为我创建表。

现在 EF 可以很好地创建我的表,除了一个小问题。它将表创建为:

人 - PersonId (PK)

富 - 个人身份(PK) - FooId (INT)

便便 - 个人身份(PK) - PooId (INT)

理想情况下,我希望表 Foo 和 Poo 中的 PersonId 是外键,而不是主键。这可能吗?尝试使用 ModelBuilder 通过以下方式执行此操作:

modelBuilder.Entity<Foo>().HasKey(x => x.FooId).ToTable("Foo");

public class Person
{
    public int PersonId { get; private set; }
}

public class Foo : Person
{
    public int FooId { get; private set; }
}

public class Poo : Person
{
    public int PooId { get; private set; }
}

【问题讨论】:

    标签: c# inheritance entity-framework-5


    【解决方案1】:

    您实现继承的方式遵循每个类型方法的表格,其中基类的 PK 是派生类的 PK以及返回基类的 FK班级。

    你想要PersonId in tables Foo and Poo to be a foreign key not as the primary key,所以通过将你的配置更改为 from

    modelBuilder.Entity<Foo>().HasKey(x => x.FooId).ToTable("Foo");
    

    modelBuilder.Entity<Foo>().ToTable("Foo");
    

    您的数据库应如下所示:

    Person - PersonId (PK)

    Foo - PersonId (PK, FK)

    Poo - PersonId (PK, FK)

    More reading on table per type inheritance.

    【讨论】:

    • 是否有可能将 PersonId 设置为仅 FK 并将 Foo 表中的 FooId 设置为 PK?
    • 是的,有可能。但在这种情况下,您应该手动创建数据库,并首先使用代码将实体映射到现有数据库。
    • 我不完全确定您想要做的事情是否可以先使用代码来完成,@KirillBestemyanov 的回答证实了这一点。看看这个链接,Ladislav 解释了如何使用设计器映射 TPT stackoverflow.com/questions/5439273/…
    • 谢谢。我正在安装 SP1 并检查可用的建模工具。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-22
    • 2021-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多