tags:

views:

28

answers:

1

Hi

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 funtion 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 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?

Michael

+1  A: 

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

Muhammad Adeel Zahid