c# - EF继承和主键

标签 c# inheritance entity-framework-5

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

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

Person - PersonId (PK)

Foo - PersonId (PK) - FooId (INT)

Poo - PersonId (PK) - PooId (INT)

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

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; }
}

最佳答案

实现继承的方式遵循每种类型表的方法,其中基类的 PK 是派生类的 PK并且返回到基类的 FK类(class)。

您想要PersonId in tables Foo and Poo to be a foreign key not as the primary key ,因此将您的配置更改为

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 .

关于c# - EF继承和主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16585458/

相关文章:

c# - 将字典字符串字符串转换为json字符串

javascript - 构造函数的对象字面量返回 toString() 方法,但不返回其他方法

c# - 修改 DAL 时出错,System.ArgumentException, "An entry with the same key already exist"

entity-framework - EF迁移:自动迁移中的RenameColumn?

c# - 无法获取我的自定义配置部分

c# - 调用不带括号的函数?

c# - 如何正确地为 XAML 中的数据绑定(bind)添加前缀(或后缀)?

java - java中的父/子构造函数

C++ 避免向下转型

ef-code-first - Entity Framework 5 代码首先将字符串全局映射到 varchar