3
我使用Linq to Sql并且无法更新多对多的关系。更新一个多对多的关系Linq to Sql
我的场景: 产品由一个或多个项目指定。当我创建了一个产品,我只是选择所需的项目,这些项目通过补充说:
product.ProductItemRel.Add(itemRel);
但什么是当我需要更新的最佳做法是什么?
我可以使我自己的更新功能找到要删除的项目和要插入的项目,但它很容易需要20行代码。
等等快速和脏:
var oldProduct = orderRepository.GetProductCRUD.FetchSingle(x => x.ProductID == product.ProductID);
//Add items
foreach (var i in items)
{
if(i not exist in oldProduct)
{
var itemRel = new ProductItemRel()
{
ItemID = i,
Product = product
};
product.ProductItemRel.Add(itemRel);
}
}
//Delete items
foreach(var p in oldProduct)
{
if(p not exist in items)
{
product.ProductItemRel.Remove(relation to delete);
}
}
另一种非常不错的方法,是只删除所有关系的添加新的。
当我需要更新多对多关系时,Linq to Sql的最佳实践是什么?