为什么导航属性有时返回null?

问题描述 投票:4回答:3

我有两个型号

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; }
}

我有数据库工厂

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

和引用databaseFactory的属性

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

我使用Autofac和regiser DatabaseFactory

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

在我的存储库中,我尝试以两种方式从导航属性中获取数据

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS83cjluOC5wbmcifQ==” alt =“在此处输入图像描述”>“ >>

第一行工作正常(CalculationType包含一个元素)

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9Dc09MRC5wbmcifQ==” alt =“在此处输入图像描述”>

但是第二行在属性CalculationType上返回null

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9pbXpTZS5wbmcifQ==” alt =“在此处输入图像描述”>

为什么?

UPDATE

我发现,如果删除行“ .InstancePerRequest()”,则一切正常。但是我不适合这个。

UPDATE2

由于某种原因,如果未创建代理类,则为该类

我有两个模型public class Indicator {public long indicatorID {get;组; } public string Name {get;组; } public int MaxPoint {get;组; } public string评论{get;组; } ...

c# asp.net asp.net-mvc entity-framework autofac
3个回答
1
投票

您的数据库上下文肯定具有不同的ProxyCreationEnabled属性值。


0
投票

尝试一下:


0
投票

我也遇到过同样的问题,首先加载页面时,它工作正常,当我刷新页面时,我得到空引用异常。就我而言,我正在使用Task

© www.soinside.com 2019 - 2024. All rights reserved.