您好,我在数据库中有更新实体的下一个代码:
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;
}
}
但我收到错误IEntityChangeTracker 的多个实例无法引用实体对象。 我应该如何处理更新的对象?我是 entityframework 6 的新手,谢谢。
UPDATE @OO 创建和更新实体。此代码有效。如您所见,创建和更新这是不同的上下文。
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;
}