在ASP.NET Core中保存模型时,我遇到了此错误The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked
。
快速解决方案不起作用:我的DbContext不是单身。此外,我只在一个型号上面对此错误,保存其他工作正确。
public class EFRepository:IRepository
{
private DatabaseContext dbcontext;
...
public void InsertOrUpdate<T>(T entity) where T : AbstractModel
{
costil_logging(entity);
if (entity==null) throw new NullReferenceException();
if(dbcontext.Set<T>().Any(x=>x.ID==entity.ID))
{
//Update
dbcontext.Entry(entity).State = EntityState.Modified; //ERROR HERE
}
else
{
entity.ID = 0;
dbcontext.Entry(entity).State = EntityState.Added;
}
dbcontext.SaveChanges();
}
}
public void ConfigureServices(IServiceCollection services)
{
...
services.AddScoped<IRepository, EFRepository>();
...
}
public class Section:AbstractModel
{
public string Name { get; set; }
public bool IsMedicalSection { get; set; }
public virtual ICollection<Category> Categories
{
get { return this.categories ?? (this.categories = new List<Category>()); }
set { categories = value; }
}
public virtual ICollection<PriceCategory> PriceCategories
{
get { return this.priceCategories ?? (this.priceCategories = new List<PriceCategory>()); }
set { priceCategories = value; }
}
[Route("section/edit")]
[HttpPost]
public IActionResult EditSave(Section section)
{
if (ModelState.IsValid)
{
repository.InsertOrUpdate(section);
return RedirectToAction("Index", "Admin");
}
//Errors displaying
return View("Edit",get_error_model(section));
}
答案 0 :(得分:1)
我认为你加载了两次对象,这就是你遇到这个问题的原因。
确保每个HTTP请求注册一次您的存储库,这样可以确保您的数据库上下文的单个实例并跟踪该对象一次。