Reputation: 14088
Hello I have next code for update entity in data base:
public async void UpdateProductFromModel(ProductEditModel model)
{
var res = await GetProduct(model.GoodId);
Mapper.Map<ProductEditModel, Goods>(model, res);
UpdateProduct(res);
}
public void UpdateProduct(Goods product)
{
try
{
using (var dbCtx = new smartbags_storeEntities())
{
dbCtx.Entry(product).State = EntityState.Modified;
dbCtx.SaveChanges();
}
}
catch (Exception ex)
{
throw ex;
}
}
public async Task<Goods> GetProduct(int id)
{
try
{
var dbCtx = new smartbags_storeEntities();
return await dbCtx.Goods.FirstOrDefaultAsync(d => d.GoodID == id);
}
catch (Exception ex)
{
throw ex;
}
}
but I am getting error An entity object cannot be referenced by multiple instances of IEntityChangeTracker. What should I do with updated object ? I am a new commer in entityframework 6 thanks.
UPDATE @O.O Create and update entity. This code working. as you can see create and update this is different context.
public bool SaveNewProduct(ProductEditModel model)
{
var prices = model.Prices;
var g = new Goods
{
Article = model.Article,
CategoryID = model.CategoryId,
Code = model.Code,
Description = model.Description,
Name = model.Name,
IsExclusive = model.IsExclusive,
IsNew = model.IsNew,
IsVisible = model.IsVisible,
};
AddNewProductToDb(g);
//update prices
if (prices.Any(d => d.IsActive) && g.Prices1.Any() && prices.Count() > 1)
{
var pr = prices.FirstOrDefault(d => d.IsActive);
g.PriceID = g.Prices1.First().PriceID;
}
UpdateProduct(g);
return true;
}
public int? AddNewProductToDb(Goods product)
{
try
{
using (var dbCtx = new smartbags_storeEntities())
{
//add standard entity into standards entitySet
dbCtx.Goods.Add(product);
//Save whole entity graph to the database
dbCtx.SaveChanges();
return product.GoodID;
}
}
catch (Exception ex)
{
throw;
}
return null;
}
Upvotes: 0
Views: 165
Reputation: 11287
You need to use the same context for the GetProduct and UpdateProduct calls. When you called GetProduct, the object it got belonged to one context and when you called UpdateProduct you created a different context and tried to use it with the Product that was still assigned to GetProduct.
One option is to pass in the context:
var dbCtx = new smartbags_storeEntities()
var res = await GetProduct(model.GoodId, dbCtx);
Mapper.Map<ProductEditModel, Goods>(model, res);
UpdateProduct(res, dbCtx);
For your Edit:
Your g
variable never has a context, so that is why you do not get this error.
Upvotes: 2