I have a scenario where I need to implement Mutually Inclusive Inheritance and I am using Entity Framework Code First as ORM. I have an abstract User class, Customer and Employee classes which are inherited from User. I have currently implemented table-per-type to model inheritance in SQL database.
Now, whenever I try to fetch both of the entities with a single db context object it gives me this exception
All objects in the EntitySet 'Context.Users' must have unique primary keys. However, an instance of type 'Employee' and an instance of type 'Customer' both have the same primary key value, 'EntitySet=Users;Id=153'
I do understand the reason why this is causing issue, but I can't find any workaround for it.
The solution that might work is that I would create a separate Primary Key for Customer and Employee and keep UserAccountId as Foreign Key, but I can't find a way to configure it through Entity Framework.
Following is a dummy code for my scenario
public abstract class UserAccount
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
}
public class Employee : UserAccount
{
}
public class Customer : UserAccount
{
}
public class CustomerConfiguration : EntityTypeConfiguration<Customer>
{
public CustomerConfiguration()
{
ToTable(nameof(Customer));
}
}
public class EmployeeConfiguration : EntityTypeConfiguration<Employee>
{
public EmployeeConfiguration()
{
ToTable(nameof(Employee));
}
}
DbSetfor these entities? Also, please show how you are adding the data.