所以我有三个表(好吧,2个表和1个映射表),如下所示:
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));
然后是这个臭臭的部分:
感谢Any<>
方法的<{3}}
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();
所以我的问题是:
这不能是正确的方式来完成我正在做的事情。如何改进代码的可维护性(和效率)?
答案 0 :(得分:1)
删除过程看起来不错,但使用Any()
而不是Where()
可以提高检查是否存在已检查的产品:
if(Product.CatalogProductMap.Any(g => g.CatalogID == catalogID))