I use Linq for Sql and don’t know how to update the many-many relationship.
My scenario: A product is defined by one or more elements. When I create a Product, I just select the elements I need and they are added:
product.ProductItemRel.Add(itemRel);
But what is the best practice when I need to update?
I could make my own update function to find elements to remove and elements to insert, but it will easily take 20 lines of code.
Etc. quick and dirty:
var oldProduct = orderRepository.GetProductCRUD.FetchSingle(x => x.ProductID == product.ProductID);
foreach (var i in items)
{
if(i not exist in oldProduct)
{
var itemRel = new ProductItemRel()
{
ItemID = i,
Product = product
};
product.ProductItemRel.Add(itemRel);
}
}
foreach(var p in oldProduct)
{
if(p not exist in items)
{
product.ProductItemRel.Remove(relation to delete);
}
}
Another and very bad way is to simply delete all relationships, add new ones.
What is the best practice in Linq to Sql when I need to update the many-many relationship?
source
share