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

3

我有三个表格(实际上是两个表格和一个映射表),如下:

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

我在页面上有一些复选框,用于更新 Product,如下所示:

<% foreach(var catalog in dataContext.Catalogs){ %>
    <!-- add a checkbox for each catalog  -->
    <input type="checkbox" name="catalog[<%= catalog.CatalogID %>]" />
<% } %>

在我的处理POST请求的代码中,我有以下内容:
 // 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));

然后是这个有点臭的部分:

已更新!

感谢Dave Swersky提供的Any<>方法。

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();

我的问题是:

这不可能是我所做的事情的正确方式。我该如何改进代码以提高可维护性(和效率)?

1个回答

1

删除过程看起来不错,但是使用Any()而不是Where()可以更有效地检查已选产品的存在:

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

可以了!谢谢。为此加1分。在我看来,Any是一个可怕的布尔方法名称。我真的希望能够通过使用JoinIntersect将这两个循环合并成一个(虽然我不确定这是否是最佳方法)。 - David Murdoch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接