要从多对多关系表中获取行,需要使用中间表中两个实体对象之间的导航属性。以下是一个示例:
模型:
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public ICollection
public class Category
{
public int CategoryId { get; set; }
public string Name { get; set; }
public ICollection
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) {
在上面的代码中,我们使用了 Include 和 ThenInclude 方法来加载 ProductCategories 集合和 Category 实体对象。这允许我们通过 product 实体对象和导航属性访问中间表中的数据。最后,我们在 View 中循环遍历 product.ProductCategories 集合,以显示每个产品相关联的类别。