我在ASP.NET MVC应用程序中使用Entity Framework 7并尝试使用 InsertOrUpdate模式 from this topic保存修改后的实体(来自HTTP POST请求)。 我也使用this post(第3种方法)。 这是我的代码:
private void insert_or_update<T>(T entity) where T : AbstractModel
{
EntityState state;
if (entity.ID == 0)
state = EntityState.Added;
else
state = EntityState.Modified;
dbcontext.Set<T>().Attach(entity); //<- ERROR THERE
dbcontext.Entry(entity).State = state;
dbcontext.SaveChanges();
}
但我有一个错误:
The instance of entity type 'Domain.Models.Section' cannot be tracked
because another instance of this type with the same key is already
being tracked.For new entities consider using an IIdentityGenerator
to generate unique key values.
我在那里检查了相同的问题,我知道,该存储库不应该作为Singleton
添加。这是我Startup.cs
的代码:
services.AddScoped<IRepository, EFRepository>();
有没有办法解决这个问题,只使用一个查询数据库?
例如,此方法使用2个查询(来自this question again)
var original = db.Users.Find(updatedUser.UserId);
if (original != null)
{
db.Entry(original).CurrentValues.SetValues(updatedUser);
db.SaveChanges();
}
UPD1: EF7没有CurrentValues
的成员EntityEntry<T>
。所以不能使用最后一种方法。
UPD2: dbContext.Set<T>().Update()
获得相同的错误。