I have one big question about TPT + EF6.
At my DB model I have one table Person
(basic information of persons in my application) and I have tables for Supplier
and Consumer
.
My classes are:
//to table dbo.Person
public class Person
{
public long Id {get; set;} //is pk
public string Name {get; set;}
}
//to table dbo.Supplier
public class Supplier : Person
{
public long Id {get; set;}//is pk and fk
public string ProductName {get; set;}
}
//to table dbo.Consumer
public class Consumer
{
public long Id {get; set;} //is pk and fk
public string budget {get; set;}
}
If I have one person that is both supplier and consumer, and I get the records from same/different DBContext
or navigate form another Entitys, then EF throws an exception:
All objects in the EntitySet
Person
must have unique primary keys. However, an instance of typeSupplier
and an instance of typeConsumer
both have the same primary key value,EntitySet=Person;ID=20
.
Is there a way to specify one discriminator in TPT inheritance? How do I solve this issue?
I suggest the pattern you actually need is Table Per Concrete Class
This can be achieved by
public class Person
{
public int Id { get; set; }
public Supplier Supplier { get; set; }
public Consumer Consumer { get; set; }
}
public class Supplier
{
public int Id { get; set; }
public string ProductName { get; set; }
}
public class Consumer
{
public int Id { get; set; }
public string Budget { get; set; }
}
Remember to put the following in your dbcontext
public DbSet<Supplier> Suppliers { get; set; }
public DbSet<Consumer> Consumers { get; set; }
public DbSet<Person> People { get; set; }
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