sql-server.net-coreentity-framework-coretable-per-type

Why do I get this TPT inheritance error, "Unable to cast object of type 'Seller' to type 'Buyer'" in my EF Core database?


This is very difficult for me to describe without an example. It took me a long time, but I've boiled it down to a simple example.

I have a database consisting of Buyers, Sellers, and Sales. However, each Buyer and each Seller inherits from Contact. It looks like this:

ER Diagram

Now if I include a single record into Sales, everything works. However, when I insert the second one, I get errors like:

Unable to cast object of type 'Seller' to type 'Buyer'.

This might make sense if the first record failed, but I don't understand why it only happens on the second one.

I've created a repository in GitHub with everything needed (database and app) to recreate the problem. You can find it here: https://github.com/plettb/EFTPT

Just to provide enough information to understand:

  1. The query: context.Sales.Include(x => x.Buyer).Include(s => s.Seller)

  2. The records:

    insert into Sales (SellerId, BuyerId, Quantity) values (7113, 7221, 1);
    insert into Sales (SellerId, BuyerId, Quantity) values (7221, 7113, 2);
    

Solution

  • It was a matter of turning the EF change tracker off.

    context.Sales.Include(x => x.Buyer).Include(s => s.Seller).AsNoTracking().ToList();
    

    Obviously this wouldn't solve the problem if there were to be any kind of editing done on the result, but in my scenario that's not an issue.