Many for Many and Linq: Updating Relationships

So, I have 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 the page for updating Product, for example:

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

In my code for processing POST, I:

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

And then this stinky part:

UPDATED!

Thanks to Dave Swirsky for the methodAny<>

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 may not be the right way to accomplish what I am doing. How can I improve the code for maintainability (and efficiency)?

+3
source share
1 answer

, Any(), Where():

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

Source: https://habr.com/ru/post/1772895/


All Articles