【发布时间】:2021-02-11 00:14:12
【问题描述】:
我正在我的 ASP.NET Core 应用程序中处理多对多关系。从在线阅读资源中,我了解到这还没有得到官方支持,因此需要一个中间类来使其正常工作。
我遇到的问题是,一旦我创建了“多对多”关系,我不知道如何最好地在我的视图中显示数据,并且我正在努力使用这种特定设置遍历所有内容。
在我的示例中,有两个表Part 和Supplier,一个Part 可以有很多Supplier,就像一个Supplier 可以有很多Part。
我做的第一件事是创建我的两个实体类Part 和Supplier
Part.cs
public class Part
{
public int PartId { get; set; }
public string PartName { get; set; }
public string PartNumber { get; set; }
public string ShortDescription { get; set; }
public string LongDescription { get; set; }
public string Category { get; set; }
//Intermediate entity
public IList<PartSupplier> PartSupplier { get; set; }
}
Supplier.cs
public class Supplier
{
public int SupplierId { get; set; }
public string SupplierName { get; set; }
public string Website { get; set; }
public int? Telephone { get; set; }
public string Email { get; set; }
//Intermediate entity
public IList<PartSupplier> PartSupplier { get; set; }
}
您将从上面的代码中看到,我放置了一个中间表,该表创建了称为 PartSupplier 的多对多关系
PartSupplier.cs
public class PartSupplier
{
public int PartId { get; set; }
public Part Part { get; set; }
public int SupplierId { get; set; }
public Supplier Supplier { get; set; }
}
此时,我转到我的数据上下文并覆盖代码的模型构建部分以利用 Fluent API。
Context.cs
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<PartSupplier>().HasKey(ps => new { ps.PartId, ps.SupplierId });
base.OnModelCreating(builder);
}
public DbSet<Part> Parts { get; set; }
public DbSet<Supplier> Suppliers { get; set; }
public DbSet<PartSupplier> PartSuppliers { get; set; }
好的,到目前为止一切顺利。现在我需要在一个视图中显示这些信息,特别是在这个视图中,我想显示所有零件,并在它们旁边显示可以购买该零件的所有可用供应商。
虽然我以以下方式加载数据,但我有点不确定应该如何构建查询。我应该打电话给中介表还是打电话Part然后包括Supplier?我不确定
PartController.cs
public IActionResult Index()
{
var data = _context.Part.Include(p => p.Supplier);
return View(data);
}
Index.cshtml
@model IEnumerable<Part>
<div class="container">
<div class="row">
<div class="col">
<h2>Parts</h2>
<a asp-action="Create" asp-controller="Parts">Add Part</a>
<table class="table">
@foreach (var part in Model)
{
<tr>
<td>
<a asp-action="Edit" asp-route-id="@part.PartId" asp-controller="Part">@part.PartName</a>
</td>
<td>
@part.PartNumber
</td>
<td>
@part.ShortDescription
</td>
<td>
...I'd like to show the suppliers here...
</td>
</tr>
}
</table>
</div>
</div>
</div>
我想我已经差不多完成了,但我真的希望有人帮助我克服这最后一道障碍。非常感谢
【问题讨论】:
标签: entity-framework asp.net-core many-to-many fluent