EF继承和主键 [英] EF inheritance and primary keys

查看:92
本文介绍了EF继承和主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm not sure whether this is possible in EF, but I am creating a bunch of classes and am trying to get EF to create the tables for me.

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

Now EF creates my tables fine, except for a minor issue. It created the tables as:

人-PersonId(PK)

Person - PersonId (PK)

Foo-PersonId(PK)-FooId(INT)

Foo - PersonId (PK) - FooId (INT)

Poo-PersonId(PK)-PooId(INT)

Poo - PersonId (PK) - PooId (INT)

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

Ideally, I want the PersonId in tables Foo and Poo to be a foreign key not as the primary key. Is this possible? Tried using the ModelBuilder to do this via:

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, 返回基类.

The way you have implemented inheritance follows the table per type approach where the PK of the base class is the PK of derived classes and also a FK back to the base class.

您希望表Foo和Poo中的 PersonId是外键而不是主键,因此请将配置从更改为

You want PersonId in tables Foo and Poo to be a foreign key not as the primary key, so by changing your configuration to from

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

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

您的数据库应如下所示:

your database should look like this:

人-PersonId(PK)

Person - PersonId (PK)

Foo-PersonId(PK,FK)

Foo - PersonId (PK, FK)

Poo-PersonId(PK,FK)

Poo - PersonId (PK, FK)

查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆