C# 多对多和Linq:更新关系

C# 多对多和Linq:更新关系,c#,asp.net,linq,linq-to-sql,C#,Asp.net,Linq,Linq To Sql,我有三个表(两个表和一个映射表),如下所示: dbo.Catalog CatalogID // int [not null] autoincrement PK dbo.Product ProductID // int [not null] autoincrement PK dbo.CatalogProductMap CatalogID // int [not null] PK ProductID // int [not null] PK 我在页面上有复选框用于更

我有三个表(两个表和一个映射表),如下所示:

dbo.Catalog
    CatalogID // int [not null] autoincrement PK
dbo.Product
    ProductID // int [not null] autoincrement PK
dbo.CatalogProductMap
    CatalogID // int [not null] PK
    ProductID // int [not null] PK
我在页面上有复选框用于更新
产品
,如下所示:

<% foreach(var catalog in dataContext.Catalogs){ %>
    <!-- add a checkbox for each catalog  -->
    <input type="checkbox" name="catalog[<%= catalog.CatalogID %>]" />
<% } %>
所以我的问题是:


这不是完成我正在做的事情的正确方法。如何提高代码的可维护性(和效率)?

删除过程对我来说很好,但是使用
Any()
而不是
Where()
,可以更有效地检查已检查产品的存在:


作品谢谢+1美元。IMO
Any
对于布尔方法来说是个可怕的名字。我真的希望我能用
Join
Intersect
做点什么,以某种方式将两个循环合并为一个循环(尽管我也不确定这是最好的方法)。
 // Regex to check Form keys and group each ID
 var rCatalog = new Regex("^catalog\\[(\\d+)\\]$");
 // gets all "checked" CatalogIDs POSTed
 IEnumerable<int> checkedCatalogs =
            Request.Form.AllKeys
                   // get only the matching keys...
                   .Where(k => rCatalog.IsMatch(k))
                   // and select the ID portion of those keys...
                   .Select(c => int.Parse(rCatalog.Match(c).Groups[1].Value));
Product Product = getProductBeingUpdated();

// iterate through each EXISTING relationship for this product
// and REMOVE it if necessary.
myDataContext.CatalogProductMaps
    .DeleteAllOnSubmit(from map in Product.CatalogProductMaps
        where !checkCatalogs.Contains(map.CatalogID)
        select map);

// iterate through each UPDATED relationship for this product
// and ADD it if necessary.
Product.CatalogProductMaps
    .AddRange(from catalogID in checkedCatalogs
        where !Product.CatalogProductMaps.Any(m => m.CatalogID == catalogID)
        select new Group{
            CatalogID = catalogID
    });


myDataContect.SubmitChanges();
if(Product.CatalogProductMap.Any(g => g.CatalogID == catalogID))