Why use Repository Pattern or please explain it to me?

前端 未结 8 1661
隐瞒了意图╮
隐瞒了意图╮ 2021-01-30 01:10

I am learning repository pattern and was reading Repository Pattern with Entity Framework 4.1 and Code First and Generic Repository Pattern - Entity Framework, ASP.NET MVC and

8条回答
  •  生来不讨喜
    2021-01-30 01:14

    When you are designing your repository classes to look alike domain object, to provide same data context to all the repositories and facilitating the implementation of unit of work, repository pattern makes sense. please find below some contrived example.

      class StudenRepository
      {
         dbcontext ctx;
         StundentRepository(dbcontext ctx)
         {
           this.ctx=ctx;
         }
         public void EnrollCourse(int courseId)
         {
           this.ctx.Students.Add(new Course(){CourseId=courseId});
         }
      }
    
      class TeacherRepository
      {
         dbcontext ctx;
         TeacherRepository(dbcontext ctx)
         {
           this.ctx=ctx;
         }
         public void EngageCourse(int courseId)
         {
           this.ctx.Teachers.Add(new Course(){CourseId=courseId});
         }
      }
    
      public class MyunitOfWork
      {
         dbcontext ctx;
         private StudentRepository _studentRepository;
         private TeacherRepository _teacherRepository;
    
         public MyunitOfWork(dbcontext ctx)
         {
           this.ctx=ctx;
         }
    
        public StudentRepository StundetRepository
        {
           get
           {       
                 if(_studentRepository==null)
                    _stundentRepository=new StundetRepository(this.ctx);
    
                return _stundentRepository;    
           }
        }
    
        public TeacherRepository TeacherRepository 
        {
           get
           {       
                 if(_teacherRepository==null)
                    _teacherRepository=new TeacherRepository (this.ctx);
    
                return _teacherRepository;    
           }
        }
    
        public void Commit()
        {
             this.ctx.SaveChanges();
        }
      }
    
    //some controller method
    public void Register(int courseId)
    {
      using(var uw=new MyunitOfWork(new context())
      {
        uw.StudentRepository.EnrollCourse(courseId);
        uw.TeacherRepository.EngageCourse(courseId);
        uw.Commit();
      }
    }
    

提交回复
热议问题