EF Core: How can I use TPH with a read-only discriminator entity property?
02:03 06 Jun 2024

Anyone know if it's possible to have a readonly property that's used as a discriminator field when using TPH inheritance. For instance, suppose you have something like this:

public enum EntityType{
  EntityA,
  EntityB
}

public abstract class Base{
  public abstract EntityType EntityType{ get; }

  // other properties/methods
}

public class Entity1{
  public override EntityType EntityType => EntityType.EntityA;

  // other properties
}

// more derived classes

Once more, it's dairly easy to map this sort of thing with NHibernate, but EF Core doesn't like it.

So, does the property really needs to have a setter for this to work?

EDIT1 Following the suggestions on the comments, I've updated the types and replaced the computed property with a readonly property:

public class Entity1{
  public override EntityType EntityType {get; } =  EntityType.EntityA;

  // other properties
}

I'm also showing the mappings I have:

public sealed class BaseTypeConfiguration: IEntityTypeConfiguration{
  public void Configure(EntityTypeBuilder builder) {
    builder.HasDiscriminator(g => g.EntityType)
           .HasValue(EntityType.EntityA)
           ....;
    builder.Property(g => g.EntityType).HasColumnName("EntityDbColumn");
  }
}

however, this still doesn't solve the issue and I get an error which says something like: "No backing field could be found for property 'base.EntityType' and the property does not have a setter.

What am I still missing?

Thanks.

Thanks

entity-framework-core tph