EntityFramework实体更新操作

  Error Info:“An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key”.

Explanation:

You must check if an entity with the same key is already tracked by the context and modify that entity instead of attaching the current one.

The code should be wrighten like this:

public override void Update(T entity) where T : IEntity {
    if (entity == null) {
        throw new ArgumentException("Cannot add a null entity.");
    }

    var entry = _context.Entry<T>(entity);

    if (entry.State == EntityState.Detached) {
        var set = _context.Set<T>();
        T attachedEntity = set.Find(entity.Id);  // You need to have access to key

        if (attachedEntity != null) {
            var attachedEntry = _context.Entry(attachedEntity);
            attachedEntry.CurrentValues.SetValues(entity);
        } else {
            entry.State = EntityState.Modified; // This should attach entity
        }
    }
}  

 

posted @ 2013-03-08 20:53  super 86  阅读(438)  评论(0编辑  收藏  举报