0

I got an n:m relationship between these three tables: Products, Keywords and ProductKeywords

Now everytime I update a Product, I provide a List<Keyword> with the new chosen keywords. This collection can contain Keywords that are already chosen as the product keywords, as well as new or removed ones. Now I want to update this in my database.

For now I'm clearing the entire ProductKeywords table where ProductKeywords.ProductId equals Product.Id. Of course this produces very much overhead as it clears out any keywords for a specific product.

Is there an easy way to update this n:m relationship without clearing the entirety of the products keywords before? So it should remove ProductKeywords that are not present in the new List<Keyword> collection anymore but still in the table, as well as add new ProductKeywords that are not present in the table yet, but in the List<Keyword>. All others (present in table and present in List<Keyword>) should remain untouched to lessen the overhead.

4

1 回答 1

1
  1. 它应该删除新列表集合中不再存在但仍在表中的 ProductKeywords,
  2. 以及添加尚未出现在表中但在列表中的新 ProductKeywords。

这是你的两个操作;只需分开做。

List<Keyword> existingKeywordsForProduct = ...;
List<Keyword> newKeywordsForProduct = ...;

var keywordsToRemove = existingKeywordsForProduct.Except(newKeywordsForProduct);
var keywordsToAdd = newKeywordsForProduct.Except(existingKeywordsForProduct);

如果现有的关键字相当小,那么您需要将它们全部拉入一个列表并使用 LINQ to Objects 进行Except调用。如果列表非常大,那么最好将其保留为 anIQueryable<Keyword>并进行两次往返,以便Except可以在 DB 端完成调用。

于 2013-05-09T15:14:57.880 回答