c# - 为什么 EF 导航属性返回 null?

标签 c# asp.net asp.net-mvc entity-framework

我有两个模型 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 enter image description here

第二行返回空集合。 enter image description here为什么?

更新 快照数据库 enter image description here enter image description here 项目链接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/

相关文章:

c# - 仅搜索日期

c# - 实现插件架构 - 动态 DLL 加载

c# - 实体中的相同类别属性与 C# 中的字典

asp.net - ASP .net 6 通过 httpclient 下载文件 - 流问题

c# - 我的类(class)应该订阅自己的公共(public)事件吗?

c# - JavaScript 中的动态 Html.ActionLink?

ASP.NET 身份数据库第一个自定义用户和角色

c# - 如何将验证处理从 Controller 操作转移到装饰器

c# - 我应该总是初始化 View 模型对象吗?

c# - 哪些体系结构可用于分解单一的 ASP.NET 网站?