Update method for generic Entity framework repository

前端 未结 1 1658
醉话见心
醉话见心 2020-12-17 04:44

I have a repository like that:

public class Repository : IRepository where T : class 
{
    private readonly IRepositoryContext _repository         


        
相关标签:
1条回答
  • 2020-12-17 05:30

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

    0 讨论(0)
提交回复
热议问题