所以我有如下三个表(好吧,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));
然后是臭臭的部分:
已更新!
感谢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();
所以我的问题是:
这不是完成我正在做的事情的正确方法。如何提高代码的可维护性(和效率)?
最佳答案
删除过程对我来说看起来不错,但是使用 Any()
而不是 Where()
可以更有效地检查已检查产品是否存在:
if(Product.CatalogProductMap.Any(g => g.CatalogID == catalogID))
关于c# - 多对多和 Linq : updating relationships,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4089608/