Reputation: 15593
I have this code:
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);
How can I do to when I write newProduct.Ingredient.Add it doesn't add a new ingredient to Ingredient table? Because when I do it, my ingredients table will have six.
IngredientImpl.Insert:
public void Insert(Ingredient ingredient)
{
Validate(ingredient);
_repository.Insert(ingredient);
}
repository:
public void Insert(Ingredient ingredient)
{
db.Ingredient.Add(ingredient);
db.SaveChanges();
}
ProductImpl:
public void Update(Product produto)
{
Validate(produto);
_repository.Update(produto);
}
Repository:
public void Update(Product product)
{
db.Entry(product).State = EntityState.Modified;
SaveChanges();
}
Upvotes: 1
Views: 123
Reputation: 109185
Seeing some of your previous questions it seems you're struggling with how to architect you data access logic. Apparently, you've chosen for separate repositories for Ingredient
and Product
. I assume that both have context of their own.
If you want to hang on to this strict separation (which may be perfectly sane) you'll have to insert the ingredients first, using the Ingredient repository. After that, you can attach them to the context in the Product repository, add them to newProduct.Ingredients
and save.
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.
Upvotes: 1