1

我有这个代码:

var newProduct = new Product(); 
newProduct.Name = "product name";
newProduct.Description = "product descvription";

ProductImpl.Insert(newProduct);

var ingredient1 = new Ingredient { Description = "ingredient 1" };
var ingredient2 = new Ingredient { Description = "ingredient 2" };
var ingredient3 = new Ingredient { Description = "ingredient 3" };

IngredientImpl.Insert(ingredient1);
IngredientImpl.Insert(ingredient2);
IngredientImpl.Insert(ingredient3);

newProduct.Ingredients.Add(ingredient1);
newProduct.Ingredients.Add(ingredient2);
newProduct.Ingredients.Add(ingredient3);

ProductImpl.Update(newProduct);

当我写 newProduct.Ingredient.Add 它不会向成分表中添加新成分时,我该怎么办?因为当我这样做时,我的配料表将有六个。


成分Impl.Insert:

public void Insert(Ingredient ingredient)
{
    Validate(ingredient);

    _repository.Insert(ingredient);
}

存储库:

public void Insert(Ingredient ingredient)
{
    db.Ingredient.Add(ingredient);

    db.SaveChanges();
}

产品说明:

public void Update(Product produto)
{
    Validate(produto);

    _repository.Update(produto);
}

存储库:

public void Update(Product product)
{
    db.Entry(product).State = EntityState.Modified;

    SaveChanges();
}
4

1 回答 1

1

看到您以前的一些问题,您似乎正在为如何构建数据访问逻辑而苦苦挣扎。Ingredient显然,您已经为和选择了单独的存储库Product。我假设两者都有自己的背景。

如果您想坚持这种严格的分离(这可能是完全理智的),您必须首先使用成分存储库插入成分。之后,您可以将它们附加到产品存储库中的上下文,将它们添加到newProduct.Ingredients并保存。

Note that you'll have two transactions. That may be OK if you decide that ingredients can have a life of their own and, thus, new ingredients can be inserted, irrespective of a subsequent failure of the product insertion.

于 2012-05-23T20:42:22.530 回答