Generic Entity Framework repository update method

entity-framework repository

Question

I have a similar repository:

public class Repository<T> : IRepository<T> where T : class 
{
    private readonly IRepositoryContext _repositoryContext;

    public Repository(IRepositoryContext repositoryContext)
    {
        _repositoryContext = repositoryContext;
        _objectSet = repositoryContext.GetObjectSet<T>();
    }

    public virtual void Update(T entity)
    {
        ObjectSet.AddObject(entity);
        _repositoryContext.ObjectContext.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
        _repositoryContext.SaveChanges();
    }
  }

That truly works for all of the entity's scalar attributes, but not for any other entities that are connected to entity properties.typeOf(T) , don't give a damn whether the entity state is changed; EF just inserts new data.

Therefore, if you, for instanceRepository<Student>.Update() even if you already have a Campus connected with that student, it will be established again with a new CampusId. If you merely updated the name, it will locate the correct Student and change his name as well.

Please demonstrate how to update this circumstance correctly.

1
4
7/27/2011 8:57:01 PM

Accepted Answer

When I intended to use a generic approach, I performed something that looked like this in your code:

public class Repository<T> : IRepository<T> where T : class 
{
    ...

    public virtual void Update(T entity)
    {
        if (context.ObjectStateManager.GetObjectStateEntry(entity).State == EntityState.Detached)
        {
            throw new InvalidOperationException(...);
        }

        _repositoryContext.SaveChanges();
    }
}

At that time, all of my code operated like follows:

var attachedEntity = repository.Find(someId);
// Merge all changes into attached entity here
repository.Update(attachedEntity);

A lot of logic is moved into your higher layer when you do this in a generic fashion. There is no more effective method for saving large disconnected object graphs (especially when many-to-many relations are involved and deleting of relations is involved).

4
7/27/2011 9:29:21 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow