I have two repositories (Cache
, EntityFramework
) for data processing. I want to get entity from cache
and update in EntityFramework
, for example error code:
User user = _cacheRepo.Get<User>(2);
user.Name = "Qolzam";
_entityFrameworkRpo.Update<User>(user);
ERORR
Can't attach entity to update
but on other hand this code works:
User user = _entityFrameworkRpo.Get<User>(2);
user.Name = "Qolzam";
_entityFrameworkRpo.Update<User>(user);
Succes: attach entity to update is ok
[Update]
public T Update<T>(T item, bool commit = true) where T : class , IBaseEntity
{
var entry = this.Entry(item);
if (entry != null)
{
entry.State = EntityState.Modified;
entry.CurrentValues.SetValues(item);
}
else
{
this.Attach(item);
}
this.SaveChanges();
return item;
}
[Exception]
System.InvalidOperationException was caught
_HResult=-2146233079
_message=Attaching an entity of type 'Domain.User' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.
HResult=-2146233079
IsTransient=false
Message=Attaching an entity of type 'Domain.User' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.
Source=EntityFramework
StackTrace:
at System.Data.Entity.Core.Objects.ObjectContext.VerifyRootForAdd(Boolean doAttach, String entitySetName, IEntityWrapper wrappedEntity, EntityEntry existingEntry, EntitySet& entitySet, Boolean& isNoOperation)
at System.Data.Entity.Core.Objects.ObjectContext.AttachTo(String entitySetName, Object entity)
at System.Data.Entity.Internal.Linq.InternalSet1.<>c__DisplayClassa.<Attach>b__9()
at System.Data.Entity.Internal.Linq.InternalSet
1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
at System.Data.Entity.Internal.Linq.InternalSet1.Attach(Object entity)
at System.Data.Entity.Internal.InternalEntityEntry.set_State(EntityState value)
at System.Data.Entity.Infrastructure.DbEntityEntry
1.set_State(EntityState value)