How to work with the inherited class field in Entity Framework

Suppose I have a main class for representing data, and this class has a configuration field. This field should answer some questions related to the main class (suppose this is one question - "IsMainClassReadyToUse"). But the internal structure of this class may be different.

Because of this, I want to create abstract class Configurator, and depending on the situation, use different ones Configuratosthat implement their functionality.

So, I have the following code:

public class SimpleConfigurator : Configurator
{
    public int FieldA { get; set; }
    public override bool IsDataClassReadyToUse()
    {
        return ParentDataClass.FieldA == FieldA;
    }
}

public class ComplexConfigurator : Configurator
{
    public virtual List<int> FieldsB { get; set; }
    public override bool IsDataClassReadyToUse()
    {
        return ParentDataClass.FieldsB.All(x => FieldsB.Any(y => y == x));
    }
}

public abstract class Configurator
{
    public int ConfiguratorId { get; set; }
    public virtual DataClass ParentDataClass { get; set; }
    public abstract bool IsDataClassReadyToUse();
}

public class DataClass
{
    public int DataClassId { get; set; }
    public virtual Configurator Configurator { get; set; }
    public int FieldA { get; set; }
    public virtual List<int> FieldsB { get; set; }
}

public class DataDbContext : DbContext
{
    public DbSet<DataClass> DataClasses { get; set; }
}

But the problem occurs when I try to use an instance DataClasswith Configuratortype ComplexConfigurator.

Due to LazyLoading, I need to load FieldsBfrom ComplexConfigurator, but abstract class Configuratordoes not contain such a field, and I cannot write code like this:

new DataDbContext().DataClasses
                   .Include(m => m.Configurator)
                   .Include(m => m.Configurator.FieldsB);

LazyLoading, DataDbContext:

public DataDbContext()
{
    Configuration.LazyLoadingEnabled = false;
}

FieldsB, null.

, ​​ Entity Framework?

, , ?

+4
1

, ,

((ComplexConfigurator)yourObject.Configurator).FieldsB

, EF List<int> ( , ), - Option List<Option> Options .

( "" SimpleConfigurator ComplexConfigurator). , DbSet<Configurator> DbContext.

EF.

0

Source: https://habr.com/ru/post/1610375/


All Articles