dotnet / dotnet/efcore

Improve the exception message for when the discriminator property was ignored

Open
#34,404 2 comments 0 reactions 0 assignees View on GitHub
area-model-building customer-reported
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

Here's how I map entities:
```
public abstract class Foo
{
public int Id { get; private set; }
public abstract int FooType { get; }
}

public sealed class Bar1 : Foo
{
public override int FooType => 1;
}

public sealed class Bar2 : Foo
{
public override int FooType => 2;
}

public sealed class Context : DbContext
{
private readonly string _connectionString;

public Context(string connectionString)
{
_connectionString = connectionString;
}

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseNpgsql(_connectionString);
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity(e =>
{
e.HasDiscriminator("FooType")
.HasValue(1)
.HasValue(2);

e.Ignore(p => p.FooType);
});

modelBuilder.Entity();
modelBuilder.Entity();
}
}
```

When I run `context.Database.EnsureCreatedAsync()`
I get `InvalidOperationException`:
>'Both 'Bar1' and 'Foo' are mapped to the table 'Foo'. All the entity types in a non-TPH hierarchy (one that doesn't have a discriminator) must be mapped to different tables. See https://go.microsoft.com/fwlink/?linkid=2130430 for more information.'

As soon as I change the name of discriminator, everything works fine.
If discriminator cannot be named as ignored property this should be in the docs and error message should be more helpful.
Here is the [repo](https://github.com/voroninp/TablePerHierarchyDiscriminatorBehavior) to reproduce the problem.

### Include provider and version information

EF Core version: 8.0.4
Database provider: PostgreSQL
Target framework: .NET 8

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.