Cadmi
Cadmi

Reputation: 73

EF Core 3.1 - DB First and Inheritance

I've created in my database 3 tables, each one with a primary key.

Person, Man, Woman

The idea is that Man and Woman inherit from Person, so their primary keys are also a FK to the Person PK.

I generate the model with the Scaffold-DbContext command and obviously I don't get any inheritance in my models, hence I explicitly do it...:

Man : Person {...}
Woman : Person {...}

However there is still something missing, since I get a runtime error: "A key cannot be configured on 'Man' because it is a derived type. The key must be configured on the root type 'Person'."

If I do it, then I get an error the other way around saying that I should set the Key not in the base class but in the derived class.

Is there any solution for that using the DB First approach?

I don't mind how internally the DB looks like (1 table is also fine with a discriminator), I just want inheritance in my model.

Thank you

Upvotes: 1

Views: 651

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239430

What you're describing is the TPT or table per type relational inheritance pattern. EF Core only supports TPH, or table per hierarchy. In TPH, all the properties for all subtypes go into the one table for the base type and a discriminator column is added to indicate the actual type. There is a long standing issue regarding this, which finally is starting to get some traction after 6 years. It's targeted for EF Core 5.0, though, so we're still a year out at least, unless it slips further.

Upvotes: 1

Related Questions