EF inheritance and primary keys

北城以北 提交于 2021-01-28 00:18:17

问题


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.

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

Person - PersonId (PK)

Foo - PersonId (PK) - FooId (INT)

Poo - PersonId (PK) - PooId (INT)

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

回答1:


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.

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");

to

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

your database should look like this:

Person - PersonId (PK)

Foo - PersonId (PK, FK)

Poo - PersonId (PK, FK)

More reading on table per type inheritance.



来源:https://stackoverflow.com/questions/16585458/ef-inheritance-and-primary-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!