当前位置: 移动技术网 > IT编程>开发语言>.net > 使用ASP.NET Web Api构建基于REST风格的服务实战系列教程——使用Repository模式构建数据库访问层

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

2018年04月13日  | 移动技术网IT编程  | 我要评论

网游之行走江湖,金钱树的养殖,边境牧羊犬的价格

前言

 

在数据访问层应用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....*/

  }

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网