在ASP.NET MVC EF中设置CRUD功能时,如何将多对多联结表显示为实体之一的一部分?

问题描述

我正在尝试使用EF来为一个我的实体与另一个实体具有多对多关系的项目支持CRUD功能。这在大多数情况下都可以正常工作,但我不知道如何将多对多关系数据作为实体之一的一部分来呈现。

我要使用的实体的脚手架模型如下

 public partial class Composition
    {
        public Composition()
        {
            CompFish = new HashSet<CompFish>();
        }

        public int CompositionId { get; set; }
        public int AccountId { get; set; }
        public int RodId { get; set; }
        public int ReelId { get; set; }
        public string Name { get; set; }

        public virtual Account Account { get; set; }
        public virtual Reel Reel { get; set; }
        public virtual Rod Rod { get; set; }
        public virtual ICollection<CompFish> CompFish { get; set; }
    }

此模型具有类型为CompFish的HashSet,它是联结表的脚手架模型,该表保留了Composition和另一个实体Fish间的关系,看起来像这样>

public partial class CompFish
    {
        public int CompositionId { get; set; }
        public int FishId { get; set; }

        public virtual Composition Composition { get; set; }
        public virtual Fish Fish { get; set; }
    }

因此,它从所连接的每个表中都有一个ID和一个实体模型。

当我想在Fish的{​​{1}}的{​​{1}}中显示CompFish的{​​{1}}属性HashSet部分时,请执行以下操作;

修改了控制器,使其包含view

Composition

并在视图中要显示数据的视图中添加CompFish循环。

public async Task<IActionResult> Index()
        {
            var projectFishContext = _context.Composition.Include(c => c.Account).Include(c => c.Reel).Include(c => c.Rod).Include(c => c.CompFish);
            return View(await projectFishContext.ToListAsync());
        }

使用foreach显示数据的方式很可能是错误的,并且由于我的主要脑力劳动,我尝试了许多不同的方式,这就是目前的样子。有一阵子,却不知道该怎么做...

任何帮助将不胜感激!

解决方法

public async Task<IActionResult> Index()
        {
            var projectFishContext = _context.Composition.Include(c => c.Account).Include(c => c.Reel).Include(c => c.Rod).Include(c => c.CompFish).ThenInclude(c => c.Fish);
            return View(await projectFishContext.ToListAsync());
        }

我错过了在集合对象上添加ThenInclude