开发者

Many to Many and Linq: updating relationships

So I've got three tables (well, 2 tables and 1 mapping table) as follows:

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

I have checkboxes on a page for updating a Product like so:

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

In my code for processing the POST I have:

 // 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 开发者_如何学Pythonportion of those keys...
                   .Select(c => int.Parse(rCatalog.Match(c).Groups[1].Value));

And then this smelly part:

UPDATED!

Thanks to Dave Swersky for the Any<> method

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

So my question is:

This can't be the right way to accomplish what I am doing. How can I improve the code for maintainability (and efficiency)?


The delete process looks good to me, but checking for the existence of checked Products can be made more efficient using Any() rather than Where():

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜