I am using Entity Framework 7 in ASP.NET MVC app and try to save modified entity (from HTTP POST request) using InsertOrUpdate pattern from this topic. I also use this post (3rd method). This is my code:
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();
}
But I've got an error:
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.
I checked same questions there and I know, that repository shouldn't be added as an Singleton
. This is my code from Startup.cs
:
services.AddScoped<IRepository, EFRepository>();
Is there any way to fix this and use only one query to database?
For example, this method using 2 queries (from this question again)
var original = db.Users.Find(updatedUser.UserId);
if (original != null)
{
db.Entry(original).CurrentValues.SetValues(updatedUser);
db.SaveChanges();
}
UPD1: EF7 has no member CurrentValues
for EntityEntry<T>
. So last method can't be used.
UPD2: dbContext.Set<T>().Update()
gets same error.