我有两个模型 1)
public class Indicator
{
public long ID { 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 virtual IList<TestEntity> TestEntitys { get; set; }
public virtual IndicatorGroup IndicatorGroup { get; set; }
}
2)
public class CalculationType
{
public long ID { 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 virtual IList<Сalculation> Calculations { get; set; }
}
我执行这段代码
var indicator = DataContext.Indicators.FirstOrDefault(i => i.ID == indicatorID);
var test = DataContext.CalculationTypes.FirstOrDefault();
第一行在导航属性 CalculationTypes 上返回 null
第二行返回空集合。 为什么?
更新 快照数据库 项目链接https://github.com/wkololo4ever/Stankin
添加了计算
public class Сalculation
{
public long ID { get; set; }
public virtual CalculationType CalculationType { get; set; }
public virtual ApplicationUser Creator { get; set; }
}
最佳答案
1)是否启用了延迟加载?如果没有,您需要使用“.Include”语法显式加载您的导航属性。
2) 你确定 EF 应该能够检测到这种关系吗?您使用代码优先还是数据库优先?
编辑:3) 您确定您的数据库中有数据并且从 Indicator 到 IndicatorGroup 的外键具有该特定记录的值吗?我这样说是因为如果根本没有数据,值“null”是有效的。
附言如果您在 Indicator 上没有看到名为“IndicatorGroupId”的外键,则表“IndicatorGroup”上可能有一个“IndicatorId”,在这种情况下 - 根据您提供的名称 - 您的数据库配置错误,您将需要使用流利的语法或数据属性来指导 EF 如何制作外键。
关于c# - 为什么 EF 导航属性返回 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29272581/