这里是我的情况 - 我有这有一个名为食谱,成分和recipes_ingredients一些表的DB。通过EF更新底层查找的更好方法?
食谱是由1+成分组成。
的recipes_ingredients具有食谱和成分表之间FKS。
是那些获得生成的类是recipe
和ingredient
和recipe
有一个看起来像这样的导航属性:
public virtual ICollection<ingredients> ingredients { get; set; }
太好了,我明白,我得到一个产生recipe
类和生成的ingredient
类recipes_ingredients
表不会获得一个类,因为EF将其视为一个导航属性。现在
,我有一个叫做SetIngredientsForRecipe
功能,看起来像这样(减去在try-catch代码为简洁起见:
public void SetIngredientsForRecipe(long recipeId, List<string> ingredients)
{
using (var db = new FoodEntities(ConnectionString, null, null))
{
var existing = GetCurrentIngredients(recipeId);
var toRemove = existing.Except(ingredients);
var toAdd = ingredients.Except(existing);
var recipe = db.recipes.Where(r => r.Id == recipeId).FirstOrDefault();
foreach (var name in toRemove)
{
var entry = recipe.ingredients.Where(i => i.Name == name).FirstOrDefault();
recipe.ingredients.Remove(entry);
}
foreach (var name in toAdd)
{
var entry = db.ingredients.Where(i => i.Name == name).FirstOrDefault();
recipe.ingredients.Add(entry);
}
db.SaveChanges();
}
}
这样做的目的,顾名思义,是更新成分表对于给定的食谱只能无论是在列表中。我仍然获得舒适与EF和想知道是否有一个更好的(更有效?)的方式来完成我想要做的事。
后续:
继ntziolis下面的建议,我选择使用
recipe.ingredients.Clear()
以清除任何在配方/成分映射,然后用它提到了对快速添加新的嘲讽。类似这样的:
foreach (var name in ingredients)
{
// Mock an ingredient since we just need the FK that is referenced
// by the mapping table - the other properties don't matter since we're
// just doing the mapping not inserting anything
recipe.ingredients.Add(new Ingredient()
{
Name = name
});
}
并且这个工作非常好。
因此,成分是否会出现在列表中,无论是添加还是去除?你不应该能够根据在UI中完成的操作来确定要采取哪种操作(并传入不同的列表)吗? – 2012-03-01 13:42:10
无论数据库当前如何表示,来自UI(“配料”参数)的列表仅具有关于应该是什么成分的“真相”。我*可能*可能在用户界面中知道这一点,但只需简单地说一下“用户界面,告诉我这个配方中应该包含什么”。但是,结果是一样的。 – itsmatt 2012-03-01 13:55:35