How to use EF Core Fluent API to get inheritance properties?
I have a base class and 2 inherited children classes:
class BaseClass
{
public string Name { get; set; }
}
class Child1 : BaseClass
{
public string Foo { get; set; }
}
class Child2 : BaseClass
{
public string Bar { get; set; }
}
class DBContext
{
...
public List<BaseClass> BaseClasses { get; set; }
...
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<BaseClass>(entity =>
{
entity.HasDiscriminator<string>("Discriminator")
.HasValue<Child1>(nameof(Child1))
.HasValue<Child2>(nameof(Child2))
.IsComplete(false);
entity.Property("Discriminator")
.IsUnicode(false)
.HasMaxLength(60);
});
}
}
But the following query:
_dBContext.BaseClasses
.Where(x => x is Child2 && EF.Property<string>(x, "Bar") == "ABC")
.ToList();
Throws the following error:
Translation of 'EF.Property(StructuralTypeShaperExpression: BaseClasses
ValueBufferExpression: ProjectionBindingExpression: EmptyProjectionMember
IsNullable: False , "Bar")' failed. Either the query source is not an entity type, or the specified property does not exist on the entity type.
It looks the issue is in IsNullable, but I have no idea how to fix it.
Thanks
_dbContext.BaseClasses.OfType<Child2>().Where(x => x.Bar == "ABC")).Where(x => x is Child2 && ((Child2)x).Bar == "ABC")? Because c# cast is the typical way of accessing derived members in EFC. OrEF.Property<string>((Child2)x, "Bar"). Looks like EFC is trying to bind propertyBartoBaseClasswhich of course doesn't exist.DbSet<Child1> Child1s { get; protected set; }etc.