开发者

Update a many to many relation Linq to Sql

I use Linq to Sql and have trouble of how to update a many to many relation.

My scenario: A product is specified by one or more items. When I create a Product, i just select the needed items and they are added by:

product.ProductItemRel.Add(itemRel);

But what is the best practice when I need to update?

I could make my own update function to find the items to delete and items to insert, but it will easily take 20 lines of code.

Etc. fast and dirty:

var oldProduct = orderRepository.GetProductCRUD.FetchSingle(x => x.ProductID == product.ProductID);

//Add items
foreach (var i in items)
{       
    if(i not exist in oldProduct)
    {                    
        var开发者_如何学Go 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);
    }
}

Another and very bad way, is to just remove all relation an add new ones.

What is the best practice in Linq to Sql when I need to update a many to many relation?


once i had been looking for "nice and clean" solution of this problem but i think society seems to have settled with "bad way".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜