Luciano Castro
Luciano Castro

Reputation: 431

EF 6 using TPT error both have the same primary key value

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 type Supplierand an instance of type Consumer 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?

Upvotes: 11

Views: 834

Answers (1)

Kirsten
Kirsten

Reputation: 18140

I suggest the pattern you actually need is Table Per Concrete Class

as illustrated by this SQL Server diagram

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; }

Upvotes: 1

Related Questions