问题描述
我正在ASP.NET Core应用程序中处理多对多关系。通过在线阅读资料,我了解到目前还没有官方的支持,因此需要一个中间类来使其全部正常工作。
我遇到的问题是,一旦创建了“多对多”关系,我就不知道如何最好地在视图中显示数据,而我正努力使用此特定设置遍历所有内容。 / p>
在我的示例中,有两个表Part
和Supplier
,一个Part
可以有很多Supplier
,就像一个Supplier
可以有很多{{1 }}。
我做的第一件事是创建两个实体类Part
和Part
Part.cs
Supplier
Supplier.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; }
}
从上面的代码中,您将看到我放置了一个中间表,该表创建了称为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.cs
PartSupplier
这时,我转到数据上下文,并覆盖代码的模型构建部分以使用Fluent API。
Context.cs
public class PartSupplier
{
public int PartId { get; set; }
public Part Part { get; set; }
public int SupplierId { get; set; }
public Supplier Supplier { get; set; }
}
好的,到目前为止很好。现在,我需要在视图中显示此信息,特别是在该视图中,我想显示所有零件,并在它们旁边显示可以从中购买零件的所有可用供应商。
尽管我以以下方式加载数据,但是在这里我不太确定如何构造查询。我应该调用中介表还是先调用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
?我不确定
PartController.cs
Supplier
Index.cshtml
public IActionResult Index()
{
var data = _context.Part.Include(p => p.Supplier);
return View(data);
}
我想我已经快知道了,但确实希望获得一些帮助来克服最后的障碍。非常感谢
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)