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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM