我有两个具有多对多关系的对象:
public class Order
{
public int OrderID { get; set; }
public string OrderName { get; set; }
public virtual Collection<Product> Products { get; set; } = new Collection<Product>();
}
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public int OrderID { get; set; }
public virtual Collection<Order> Orders { get; set; } = new Collection<Order>();
}
// Mapping table
public class OrderProduct
{
public int OrderId { get; set; }
public Order Order { get; set; }
public int ProductId { get; set; }
public Product Product { get; set; }
}
我想向数据库中添加一个包含现有产品集合的新订单(我的API将有一个ProductID数组输入),所以我的执行方式如下:
private void AddOrder(int[] productIDs)
{
Order newOrder = new Order();
newOrder.Name = "New Order";
// Here I have no clue which would be the correct way...Should I do
// Approach A(fetch each related entity - Product from database then add them into the collection of my new base entity - Order):
productIDs.ToList().Foreach(p =>
{
newOrder.Products.Add(_dbContext.Product.FindById(p))
}
);
_dbContext.Orders.Add(newOrder);
var newOrderID = _dbContext.SaveChanges();
// then fetch each product from database and add my new Order to its collection and save
productIDs.ToList().Foreach(p =>
{
var existedProductFromDb = _dbContext.Product.FindById(p);
existedProductFromDb.Orders.Add(newOrder);
_dbContext.SaveChanges();
}
);
}
我真的需要在Entity Framework Core中订购和产品之间的映射表吗?否则,应对上述情况的正确方法是什么?
答案 0 :(得分:3)
您的实体使用联接表不表示多对多关系。实际上,您根本不使用联接表。
因此,请先修复您的实体:
public class Order
{
public int OrderID {get;set;}
public string OrderName {get;set;}
public ICollection<OrderProduct> Products { get; set; } = new HashSet<OrderProduct>();
}
public class Product
{
public int ProductID {get;set;}
public string ProductName {get;set;}
public ICollection<OrderProduct> Orders { get; set; } = new HashSet<OrderProduct>();
}
包含许多Order
的新Product
就像新OrderProduct
的集合一样简单:
private void AddOrder(int[] productIDs)
{
Order newOrder = new Order();
newOrder.Name = "New Order";
foreach (int productId in productIDs)
{
newOrder.Products.Add(new OrderProduct { ProductId = productId });
}
_dbContext.Orders.Add(newOrder);
_dbContext.SaveChanges();
}
还要注意,SaveChanges
返回数据库中受影响的行数,而不是插入项的ID。