问题描述
以下作品中的code,然而,我怀疑我失去了一些东西。是否有一个'好'的方式?
The code below works, however, I suspect that I'm missing something. Is there a 'better' way?
private void UpdateNew(MarketProduct marketproduct)
{
context.MarketCategories.Load();
MarketProduct dbProd = context.MarketProducts.Find(marketproduct.Id);
dbProd.Categories.Clear();
foreach (var c in marketproduct.Categories ?? Enumerable.Empty<MarketCategory>())
{
var cc = context.MarketCategories.Find(c.Id);
dbProd.Categories.Add(cc);
}
context.Entry(dbProd).CurrentValues.SetValues(marketproduct);
}
我认为这将是可能做到这一点,而无需使用查找
推荐答案
您有三个数据库查询:1) context.MarketCategories.Load()
(希望类别表小,否则这将是一个不走的,因为它加载整个表到内存中),2) ...找
3) dbProd .Categories.Clear()
:这里必须涉及延迟加载,否则这会崩溃,因为 dbProd.Categories
是空
。
You have three database queries: 1) context.MarketCategories.Load()
(hopefully the category table is small, otherwise this would be a no-go as it loads the whole table into memory), 2) ...Find
and 3) dbProd.Categories.Clear()
: Here must be a lazy loading involved, otherwise this would crash because dbProd.Categories
would be null
.
这是另一种与单个数据库查询来更新如下:
An alternative to update with a single database query is the following:
private void UpdateNew(MarketProduct marketproduct)
{
MarketProduct dbProd = context.MarketProducts
.Include(p => p.Categories)
.Single(p => p.Id == marketproduct.Id);
var categories = marketproduct.Categories
?? Enumerable.Empty<MarketCategory>();
foreach (var category in categories)
{
if (!dbProd.Categories.Any(c => c.Id == category.Id))
{
// means: category is new
context.MarketCategories.Attach(category);
dbProd.Categories.Add(category);
}
}
foreach (var category in dbProd.Categories.ToList())
{
if (!categories.Any(c => c.Id == category.Id))
// means: category has been removed
dbProd.Categories.Remove(category);
}
context.Entry(dbProd).CurrentValues.SetValues(marketproduct);
// context.SaveChanges() somewhere
}
这篇关于实体框架4.1。更新许多到许多关系。这是正确的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!