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

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

前言

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

构建Repository

在构建Repository模式以前,咱们先列举在咱们项目中将要使用到的用例,因为咱们项目的重点是Web Api,因此Repository的构建相对比较简单,并无用泛型基类的方式来构建。设计模式

查询全部的科目,经过ID得到某个科目。函数

查询全部的课程以及关联的对象(导师和科目) 。性能

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

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

根据课程ID查询全部报读的学生信息code

经过用户名查询学生htm

经过用户名和密码验证学生信息对象

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

学生和课程的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

相关文章
相关标签/搜索