我有两个具有多对多关系的实体(Product和Supply),在它们之间还有一个实体,它拥有两个ID(SupplyProduct)。
我的实体:
public class Product
{
[Key]
public int ProductId { get; set; }
[Required]
public string? ProductName { get; set; }
[Required]
[Column(TypeName = "decimal(6,2)")]
public decimal UnitPrice { get; set; }
public int Quantity { get; set; }
public string? Brand { get; set; }
public DateTime CreatedDateTime { get; set; } = DateTime.Now;
//Many to many relationship between the products and the stocks
public virtual ICollection<SupplyProduct>? SupplyProducts { get; set; }
}
public class Supply
{
[Key]
[Required]
public int SupplyId { get; set; }
[Required]
[DisplayName("Supply's Label")]
public string? Label { get; set; }
//One to many relationship between the Stock and the Merchant
public Merchant? Merchant { get; set; }
//Many to many relationship between the stocks and the products
public virtual ICollection<SupplyProduct>? SupplyProducts { get; set; }
}
public class SupplyProduct
{
[Key]
public int SupplyId { get; set; }
public virtual Supply? Supply { get; set; }
[Key]
public int ProductId { get; set; }
public virtual Product? Product { get; set; }
}
我想在创建产品时将供应分配给产品。然后显示供应及其关联产品
这是我的产品控制器:
ProductsController.cs
public class ProductController : Controller
{
private readonly ApplicationDbContext _db;
public ProductController(ApplicationDbContext db)
{
_db = db;
}
// GET: ProductController
public ActionResult Index()
{
IEnumerable<Product> ProductsList = _db.Products;
return View(ProductsList);
}
// GET: ProductController/Create
public ActionResult Create()
{
IEnumerable<Supply> SuppliesList = _db.Supplies.Include(s => s.Merchant);
ViewBag.Supplies = SuppliesList;
return View();
}
// POST: ProductController/Create
[HttpPost]
public ActionResult Create(Product model, List<int> supplyIds)
{
_db.Products.Add(model);
_db.SaveChanges();
SupplyProduct SP = new();
foreach (var supplyId in supplyIds)
{
SP.SupplyId = supplyId;
SP.ProductId = model.ProductId;
SP.Product = model;
SP.Supply = _db.Supplies.Where(x => x.SupplyId == supplyId).FirstOrDefault();
}
_db.SupplyProducts.Add(SP);
_db.SaveChanges();
return RedirectToAction(nameof(Index));
}
}
请检查我的postCreate
方法是否正确,以及如何在Index
方法中将Supplies返回到索引视图时获取Products数据?
非常感谢您的帮助和快乐的编码:D
2条答案
按热度按时间ohfgkhjo1#
如果除了SupplyProduct之外没有其他属性,您可以删除SupplyProduct表,因为多对多不需要它。
只需一次查询即可将产品添加到供应(在代码中,您查询
supplyIds
中的每个人ID)从数据库获取
保存新产品供应
wlzqhblo2#
你可以请检查我的职位创建方法,如果它是因为它应该是
按如下所示修改代码,否则第二个电源将始终存储在
supplyIds
中:如何在将Index方法中的Supplies返回到索引视图时获取Products数据?
更改您的索引方法如下: