I've got an strange problem with TPC inheritance using C# Entity Framework Codefirst and Fluent Api.
I have 3 Classes named Person
, Invoice
and PeriodicInvoice
as you can see below.
Here is a summary of my code:
Invoice
class and its configuration class:
public class Invoice : InvoiceBase
{
public Person User { get; set; }
}
public class InvoiceConfig : EntityTypeConfiguration<Invoice>
{
public InvoiceConfig()
{
this.Map(m => { m.MapInheritedProperties(); m.ToTable("Invoices"); });
}
}
PeriodicInvoice
class and its configuration:
public class PeriodicInvoice : InvoiceBase
{
// Some extra properties.
}
public class PeriodicInvoiceConfig : EntityTypeConfiguration<PeriodicInvoice>
{
public PeriodicInvoiceConfig()
{
this.Property(x => x.SuspendOnExpire).IsRequired();
this.Map(m => { m.MapInheritedProperties(); m.toTable("PeriodicInvoices"); });
}
}
When I run the code, this error appears:
The association 'Invoice_User' between entity types 'Invoice' and 'Person' is invalid. In a TPC hierarchy independent associations are only allowed on the most derived types.
I know it means that I should include the property User
to class PeriodicInvoice
and don't use it in class Invoice
.
But, Isn't there any other way to solve this problem? Thanks.
In TPC inheritance you can't have a field in parent class that points to another table because you are trying to point two tables to another table and one table that tries to point to one of these two tables using only one foreign key (and that's impossible!).
I suggest you to use TPT. This link can help you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With