Search code examples
c#asp.netasp.net-mvcentity-frameworkautofac

Why navigation property sometimes return null?


I have two models

public class Indicator
{
    public long IndicatorID { get; set; }
    public string Name { get; set; }
    public int MaxPoint { get; set; }
    public string Comment { get; set; }
    public DateTime DateChanged { get; set; }
    public DateTime DateCreated { get; set; }

    public virtual IList<CalculationType> CalculationTypes { get; set; }
}

public class CalculationType
{
    public long CalculationTypeID { get; set; }
    public string UnitName { get; set; }
    public int Point { get; set; }
    public DateTime DateCreated { get; set; }
    public DateTime DateChanged { get; set; }

    public virtual Indicator Indicator { get; set; }
}

I have database factory

public class DatabaseFactory
{
    private StankinQuestionnaireEntities dataContext;
    public StankinQuestionnaireEntities Get()
    {
        return dataContext ?? (dataContext = new StankinQuestionnaireEntities());
    }
}

and property which refers to databaseFactory

protected StankinQuestionnaireEntities DataContext
{
    get { return dataContext ?? (dataContext = DatabaseFactory.Get()); }
}

I use Autofac and regiser DatabaseFactory

builder.RegisterType<DatabaseFactory>().As<IDatabaseFactory>().InstancePerRequest();

on my repository i trying get data from navigation property in two ways

enter image description here

first line works fine(CalculationType contains one element)

enter image description here

but second line return null on property CalculationType

enter image description here

Why?

UPDATE I found that if remove the line ".InstancePerRequest()", everything works. But I do not fit this.

UPDATE2 for some reason, ef not created Proxy class


Solution

  • You definitely have different values of ProxyCreationEnabled property for your database contexts.

    If you look at the types of the picked entities in your screenshots, you can see that the first one has type System.Data.Entity.DynamicProxies.Indicator_E... and the second one has type StankinQuestionnaire.Model.Indicator.

    That means that ProxyCreationEnabled is true for the first database context and the property is false for the second one. So, lazy loading does not work in the second case.

    Try to search where ProxyCreationEnabled is set in your project, probably you have more than one place for that.