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){ %>
<input type="checkbox" name="catalog[<%= catalog.CatalogID %>]" />
<% } %>
In my code for processing POST, I:
var rCatalog = new Regex("^catalog\\[(\\d+)\\]$");
IEnumerable<int> checkedCatalogs =
Request.Form.AllKeys
.Where(k => rCatalog.IsMatch(k))
.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)?
source
share