使用ASP.NET Web Api构建基于REST风格的服务实战系列教程【二】——使用Repository模式构建数据库访问层

系列导航地址http://www.cnblogs.com/fzrain/p/3490137.html

前言

在数据访问层应用Repository模式来隔离对领域对象的细节操作是很有意义的。它位于映射层之上作为对于数据进行CRUD操作的一个抽象层。在Repository模式中,我们可以像操作内存里的集合一样来操作数据,而Repository则负责把我们的操作更新到数据库中。

构建Repository

在构建Repository模式之前,我们先列举在我们项目中将要使用到的用例,由于我们项目的重点是Web Api,所以Repository的构建相对比较简单,并没有用泛型基类的方式来构建。

查询所有的科目,通过ID获得某个科目。

查询所有的课程以及关联的对象(导师和科目) 。

根据ID获取某个课程以及关联的对象(导师,学科以及参与该课程的学生)

查询所有的学生以及相关对象(参与的课程,课程所在学科,导师)

根据课程ID查询所有报读的学生信息

通过用户名查询学生

通过用户名和密码验证学生信息

为注册过的学生提供选课功能

学生和课程的CRUD

创建ILearningRepository接口来定义所有的用例:

public interface ILearningRepository
    {
        IQueryable<Subject> GetAllSubjects();
        Subject GetSubject(int subjectId);

        IQueryable<Course> GetCoursesBySubject(int subjectId);
        
        IQueryable<Course> GetAllCourses();
        Course GetCourse(int courseId);
        bool CourseExists(int courseId);

        IQueryable<Student> GetAllStudentsWithEnrollments();
        IQueryable<Student> GetAllStudentsSummary();

        IQueryable<Student> GetEnrolledStudentsInCourse(int courseId);
        Student GetStudentEnrollments(string userName);
        Student GetStudent(string userName);

        Tutor GetTutor(int tutorId);
        
        bool LoginStudent(string userName, string password);

        bool Insert(Student student);
        bool Update(Student originalStudent, Student updatedStudent);
        bool DeleteStudent(int id);

        int EnrollStudentInCourse(int studentId, int courseId, Enrollment enrollment);

        bool Insert(Course course);
        bool Update(Course originalCourse, Course updatedCourse);
        bool DeleteCourse(int id);

        bool SaveAll();
    }

上述的接口中已经包含了我们Api中所有需要的操作。特别说明一下在这里对于集合我们都返回IQueryable<>类型,因为这个类型能够做到按需查询,延迟加载——当我们进行多条件复合检索或者分页,排序的时候,IQueryable<>类型不会立即访问数据库,而是在集合被迭代的时候(在前台foreach展示数据的时候)才去数据库查询加载,这样可以提高访问性能,避免查询出一些不必要的数据。

现在我们新建“learningrepository”类实现ILearningRepository,在这里我给出部分实现,剩下的可以在本章最后下载源码获得:

public class LearningRepository : ILearningRepository
 {
     private LearningContext _ctx;
     public LearningRepository(LearningContext ctx)
     {
         _ctx = ctx;
     }
 
 public IQueryable&lt;Subject&gt; GetAllSubjects()
     {
         return _ctx.Subjects.AsQueryable();
     }
 
 /*Rest of methods implementation goes here....*/
  }

在learningrepository的构造函数中我们可以发现我们需求一个learningrepository类型来初始化我们的_ctx。这种设计模式叫做依赖注入,简单的来说就是对象的创建是通过第三方容器来实现的,而不是直接new。这样做有利于模块与模块间的耦合降低,关于更多依赖注入的信息,请参考:http://www.cnblogs.com/tylerdonet/p/3297915.html

总结

到此为止,我们的数据访问层就算基本完成了,Web Api的准备工作也就完了。从下一章开始,本次的主角Web Api就要闪亮登场了。

本章源码:http://yun.baidu.com/s/1o6wf1KQ

posted @ 2014-01-03 16:45  Eric0229  阅读(7049)  评论(12编辑  收藏  举报