ASP.NETCoreMVCEnityFramework-如何从多对多关系表中获取行?
创始人
2024-09-18 00:30:54
0

要从多对多关系表中获取行,需要使用中间表中两个实体对象之间的导航属性。以下是一个示例:

模型:

public class Product { public int ProductId { get; set; } public string Name { get; set; } public ICollection ProductCategories { get; set; } }

public class Category { public int CategoryId { get; set; } public string Name { get; set; } public ICollection ProductCategories { get; set; } }

public class ProductCategory { public int ProductId { get; set; } public Product Product { get; set; } public int CategoryId { get; set; } public Category Category { get; set; } }

Controller:

public class ProductController : Controller { private readonly ApplicationDbContext _context;

public ProductController(ApplicationDbContext context)
{
    _context = context;
}

public IActionResult Index()
{
    var products = _context.Products
        .Include(p => p.ProductCategories)
        .ThenInclude(pc => pc.Category)
        .ToList();

    return View(products);
}

}

View:

@foreach (var product in Model) {

@product.Name

    @foreach (var pc in product.ProductCategories) {
  • @pc.Category.Name
  • }
}

在上面的代码中,我们使用了 Include 和 ThenInclude 方法来加载 ProductCategories 集合和 Category 实体对象。这允许我们通过 product 实体对象和导航属性访问中间表中的数据。最后,我们在 View 中循环遍历 product.ProductCategories 集合,以显示每个产品相关联的类别。

相关内容

热门资讯

重大来袭!爱来掌中宝有没有挂(... 较多好评“微乐万能挂官网”开挂(透视)辅助教程 了解更多开挂安装加(136704302)微信号是一款...
新手必备!心悦透视辅助器免费(... 新手必备!心悦透视辅助器免费(透视)wepoker游戏安装教程(wpk教程确实有挂)这是一款可以让一...
一起来探讨!新道游辅助器透视挂... 一起来探讨!新道游辅助器透视挂(透视)pokemmo脚本最新版(存在挂教程有挂教程);无需打开直接搜...
透视模拟器!好玩贰柒拾辅助(透... 透视模拟器!好玩贰柒拾辅助(透视)werplan透视挂(AI教程有挂讲解);无需打开直接搜索薇:13...
玩家必知教程!新道游辅助器免费... 哈糖大菠萝可以开挂吗是一款专注玩家量身打造的游戏记牌类型软件,在哈糖大菠萝可以开挂吗这款游戏中我们可...
如何分辨真伪!凑一桌关春天怎么... 较多好评“微乐万能挂官网”开挂(透视)辅助教程 了解更多开挂安装加(136704302)微信号是一款...
记者发布!途游辅助器(透视)w... 记者发布!途游辅助器(透视)wpk辅助哪里买(技巧教程证实有挂) 了解更多开挂安装加(1367043...
重磅来袭!四川皮皮辅助(透视)... 重磅来袭!四川皮皮辅助(透视)佛手在线大菠萝为什么都输(存在挂教程了解有挂);无需打开直接搜索微信(...
透视好友!小南娱乐科技(透视)... 大家好,今天小编来为大家解答小南娱乐科技这个问题咨询软件客服可以免费测试直接加微信(13670430...
总算了解!新久久辅助器(透视)... 新久久辅助器 无需打开直接搜索微信:136704302本司针对手游进行,选择我们的四大理由: 1、软...