Update method for generic Entity framework repository

北慕城南 提交于 2019-11-29 04:56:04

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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!