efcore icon indicating copy to clipboard operation
efcore copied to clipboard

No discriminators matched the discriminator value in EF Core 5

Open razzemans opened this issue 5 years ago • 2 comments

I'm running into an issue which I think starting occurring after upgrading to EF Core 5. We have a TPH inheritance pattern, but we have a discriminator value in the database that is not mapped to an actual entity (reasons can be deploying different branches on a testenvironment).

I'm quite sure this used to work in EF Core 3.1, now it throws an exception on the following code:

dbContext.PageVersions.Where(...);

The exception is:

Unable to materialize entity instance of type 'PageVersion'. No discriminators matched the discriminator value 'XXX'

The way we register the entities (this code has not changed since 1.0):

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
        // Get all the classes that inherit from `PageVersion`.
	foreach (Type type in typeResolver.GetPageVersionTypes())
	{
		modelBuilder.Entity(type).HasBaseType(type.GetTypeInfo().BaseType);
	}
}

I tried changing the line to:

modelBuilder.Entity(type).HasDiscriminator().IsComplete(false);

But I still get the same error (I expected that to fix the issue). Is there a way around this? I would like to have an option where EF Core just "filters" out any entities it cannot map to a class, as it did before. I cannot find a breaking change covering this or a way to work around this.

EF Core version: 5.0.5 Database provider: Microsoft.EntityFrameworkCore.SqlServer Target framework: .NET 5.0 Operating system: Windows 10 IDE: Visual Studio 2019 16.3

razzemans avatar May 31 '21 10:05 razzemans

The solution for this is indeed telling EF Core that you may have unknown discriminator values in the database by configuring the discriminator with IsComplete(false) - doing this adds the discriminator check as it was in 3.1 and prevents the error. I've done a quick test below and everything seems to work fine; if it's not working for you, can you please submit a runnable code sample which reproduces the error, or simply tweak the below code sample?

Attempted repro
await using var ctx = new BlogContext();
await ctx.Database.EnsureDeletedAsync();
await ctx.Database.EnsureCreatedAsync();

ctx.Database.OpenConnection();
try
{
    using var cmd = ctx.Database.GetDbConnection().CreateCommand();
    cmd.CommandText = @"INSERT INTO [Blogs] ([Discriminator], [Name]) VALUES ('Unknown discriminator', 'unknown')";
    cmd.ExecuteNonQuery();
}
finally
{
    ctx.Database.CloseConnection();
}

_ = ctx.Blogs.ToList();

public class BlogContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    static ILoggerFactory ContextLoggerFactory
        => LoggerFactory.Create(b => b.AddConsole().AddFilter("", LogLevel.Information));

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseSqlServer(@"Server=localhost;Database=test;User=SA;Password=Abcd5678;Connect Timeout=60;ConnectRetryCount=0")
            .EnableSensitiveDataLogging()
            .UseLoggerFactory(ContextLoggerFactory);

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>().HasDiscriminator().IsComplete(false); // The important line
        modelBuilder.Entity<Blog>().HasData(new Blog { Id = 1, Name = "foo" });
        modelBuilder.Entity<SpecialBlog>().HasData(new SpecialBlog { Id = 2, Name = "bar", SpecialProperty = "baz" });
    }
}

public class Blog
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class SpecialBlog : Blog
{
    public string SpecialProperty { get; set; }
}

roji avatar May 31 '21 10:05 roji

Strange, it seems to indeed work. I'm 100% sure I compiled and ran it with the .IsComplete(false) and it didn't work. My bad then, thanks a lot for the quick reply!

razzemans avatar May 31 '21 11:05 razzemans