Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF inheritance and primary keys

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; }
}
like image 267
Dr Schizo Avatar asked May 15 '26 12:05

Dr Schizo


1 Answers

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.

like image 200
MattSull Avatar answered May 18 '26 01:05

MattSull