Generic Entity Framework repository update method

entity-framework repository

Question

I have a repository like that:

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();
    }
  }

Now that actually works for all scalar properties of the entity, but all the other entities that associated with properties of entity typeOf(T), don't care that entity state is modified, and EF simply adds new data.

So, if you do for example Repository<Student>.Update(), and you only changed the name, it will find the right Student and change his name, but it also will change the Campus, although you already have a Campus associated with that student, it will be created again with a different CampusId.

Show me please the correct way to do updates in this situation.

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

Accepted Answer

What I did when I wanted to follow generic approach was translated to your code something like:

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();
    }
}

All my code then worked like:

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

=> Doing this in generic way moves a lot of logic into your upper layer. There is no better way how to save big detached 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