【问题标题】:Error in getting navigation property in a many to many relationship in entity framework core在实体框架核心的多对多关系中获取导航属性时出错
【发布时间】:2020-03-19 14:00:46
【问题描述】:

我有两个以多对多关系连接的实体,如下所示

public class Fee
{
    public int Id { get; set; }
    [Required]
    public string Label { get; set; }
    public string Description { get; set; }

   ----Ignored for brevity----

    public virtual ICollection<ClassFee> ClassFees { get; set; }

}

public class StudentClass
{

    public int Id { get; set; }
    public string Label { get; set; }
    ---Ignored for brevity---
    public virtual ICollection<ClassFee> ClassFees { get; set; }

}

 public class ClassFee
{
    public int Id { get; set; }
    [Display(Name ="Fee")]
    public int FeeId { get; set; }
    [Display(Name ="Class")]
    public int ClassId { get; set; }

    ---ignored for brevity---

    [ForeignKey("FeeId")]
    public Fee Fee { get; set; }

    [ForeignKey("ClassId")]
    public StudentClass Class { get; set; }
}

以下是我的 FeesController 类,我打算在其中获取给定费用的详细信息以及费用适用的类列表

public async Task<IActionResult> Details(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var fee = await _context.Fees
            .Include(cf => cf.ClassFees)
            .FirstOrDefaultAsync(m => m.Id == id);
        if (fee == null)
        {
            return NotFound();
        }

        return View(fee);
    }

我期待这样,我应该能够通过调用classFeeEntityInstance.class.label 在视图中查看费用类 获取类的标签,但它返回 null。此外,当我在方法上设置断点并运行代码时,classfee.class 将返回为 null

我还尝试执行以下操作以查看是否可以在查询中急切地加载课程,但似乎无法使用 ThenInclude caluse 从 classfee 中找到课程,如下所示

.Include(cf => cf.ClassFees).ThenInclude(f=>f.Class)

但此时 f.Class 不存在,因为 Visual Studio 中的智能没有建议它,它立即强调它我尝试添加它。

以下是我希望如何在我的视图中使用 classFees 下的课程

@foreach (ClassFee classFee in Model.ClassFees)
{
   @classFee.Class.Label
}

但是Class.Label在代码运行时抛出了空引用异常

应用程序是在 ASP.NET-Core 3.1 和 Entity Framework 3.1 上构建的

我将不胜感激任何解决此问题的指南 谢谢

【问题讨论】:

  • 您是否尝试过使用ThenInclude 构建它?有一个带有 Intellisense 的 known issue ThenInclude
  • @TylerHundley,它奏效了。哇!非常感谢。请回复您的评论,以便我接受。
  • 完成。是的,前几天我遇到了这个问题,并试图弄清楚发生了什么,结果发现它像你期望的那样工作,只是没有告诉你。

标签: c# entity-framework-core asp.net-core-mvc many-to-many navigation-properties


【解决方案1】:

继续尝试使用ThenInclude 构建它,它应该可以工作。有一个带有 Intellisense 的 known issueThenInclude

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多