所以我有三个表(好的,两个表和一个映射表),如下所示:
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 %>]" />
<% } %>
在我处理帖子的代码中,我有:
// 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();
所以我的问题是:
这不可能是
正确的
完成我正在做的事情的方法。如何改进可维护性(和效率)代码?