使用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

相關文章
相關標籤/搜索