c# entity framework: correct use of DBContext class inside your repository class

前端 未结 10 1619
伪装坚强ぢ
伪装坚强ぢ 2020-12-02 10:59

I used to implement my repository classes as you can see below

public Class MyRepository
{
      private MyDbContext _context; 

      public MyRepository(My         


        
10条回答
  •  悲哀的现实
    2020-12-02 11:49

    Let's assume, you have more than one repository and you need to update 2 records from different repositories. And you need to do it transactional (if one fails - both updates rollbacks):

    var repositoryA = GetRepository();
    var repositoryB = GetRepository();
    
    repository.Update(entityA);
    repository.Update(entityB);
    

    So, if you have own DbContext for each repository (case 2), you need to use TransactionScope to achieve this.

    Better way - have one shared DbContext for one operation (for one call, for one unit of work). So, DbContext can manage transaction. EF is quite for that. You can create only one DbContext, make all changes in many repositories, call SaveChanges once, dispose it after all operations and work is done.

    Here is example of UnitOfWork pattern implementation.

    Your second way can be good for read-only operations.

提交回复
热议问题