Search code examples
asp.netentity-frameworkxunit

Entity Framework Linq Query OfType<T> fails with InvalidCastException when called from testing assembly


I'm running a net8.0 aspnet server using entity framework. One table in my database is for "Users", but it contains 2 different types via a discriminator "Buyer" and "Seller". In the code, Buyer and Seller are both subclasses of User

In the app, I specify a type of user using linq like this

Buyer buyer = context.Users
    .OfType<Buyer>()
    .Where(x => x.Id == userGuid)
    .FirstOrDefault()

this works fine, except when I try and do the exact same thing from my xunit testing project. when I do, I get a InvalidCastException Unable to cast object of type 'App.Data.User' to type 'App.Data.Buyer'.

I'm not mocking the database or anything. it's the same type of database for the development server and testing.

services.AddDbContext<AppDbContext>(options =>
{
  options.UseSqlServer(connectionString);
}

Solution

  • Figured it out. The difference between the live and test is that the player was just created and added to the database like this

    db.Users.Add(new User()
    {
        discriminator = "Buyer"
    });
    

    instead of like this

    db.Users.Add(new Buyer());
    

    if an instance is already attached when you request it from the DbSet, it will return the existing c# class, which was of type User not Buyer. after the database seeding step is finished, the dbcontext is destroyed before testing starts so the object is respawned from the table as a Buyer as expected

    I didn't write that code so it took some digging to find the source