【发布时间】:2015-03-28 12:25:22
【问题描述】:
我有两个模型
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 和注册数据库工厂
builder.RegisterType<DatabaseFactory>().As<IDatabaseFactory>().InstancePerRequest();
在我的存储库中,我尝试通过两种方式从导航属性中获取数据
第一行工作正常(CalculationType 包含一个元素)
但第二行在属性 CalculationType 上返回 null
为什么?
更新 我发现如果删除“.InstancePerRequest()”行,一切正常。但我不适合这个。
UPDATE2由于某种原因,没有创建代理类
【问题讨论】:
-
在第一种情况下,您有一个代理(查看其运行时类型)。在第二种情况下,您有基本模型类型。您期望的导航属性的行为仅适用于代理,因为代理是您的基本模型类型的子类型,它覆盖您的导航属性以提供简单和延迟加载。如果没有代理,框架就没有机会覆盖导航属性并为您提供所需的行为。
-
@TheodorosChatzigiannakis 但为什么 ef 没有创建代理类? ProxyEnable 设置为真savepic.net/6498011.png
标签: c# asp.net asp.net-mvc entity-framework autofac