如何解决在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; }
}
当我想在Fish
的{{1}}的{{1}}中显示CompFish
的{{1}}属性的HashSet
部分时,请执行以下操作;
修改了控制器,使其包含view
Composition
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。