Reputation: 4147
Currently, I implemented this Update function in my Generic Repository
public virtual void Update(TEntity entity)
{
var dbContext = _context as DbContext;
var entry = dbContext.Entry(entity);
var key = GetPrimaryKey(entry);
if (entry.State == EntityState.Detached)
{
var currentEntry = _dbSet.Find(key);
if (currentEntry != null)
{
dbContext.Entry(currentEntry).CurrentValues.SetValues(entity);
dbContext.Entry(currentEntry).State = EntityState.Modified;
}
else
{
_dbSet.Attach(entity);
entry.State = EntityState.Modified;
}
}
dbContext.SaveChanges();
}
I tried debug and found that the value of the "currentEntry" is updated to the same as the "entity". But the data in the database isn't updated. Please help if you have any solution for this.
Upvotes: 0
Views: 2337
Reputation: 5137
I have a simpler working version of Update method on my generic repository, see if that helps:
public int Update<T>(T item) where T : class
{
Guard.ArgumentNotNull(item, "item");
Set<T>().Attach(item);
// Calling State on an entity in the Detached state will call DetectChanges()
// which is required to force an update.
Entry(item).State = EntityState.Modified;
return SaveChanges();
}
And since EF track the entity internally, calling this method would throw exception "An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.”
I have solved it by disabling entity tracking in my Query method as below:
public IQueryable<T> Query<T>() where T : class
{
return Set<T>().AsNoTracking();
}
Upvotes: 2