Writing Repository Methods
In this lesson, we're going to write the methods in our Repository
Writing repository methods#
We have added ICourseRepository to our ConfigureServices method in the last lesson. Let's go back to the CourseRepository class and start implementing it. Before writing any code, I would like to remind you that we are going to inject our Store context here and remove it from the controllers. Our controllers will then use the repository instead.
We need to create a constructor now. Go to the CourseRepository and open quick fix using command and period. Now click on generateConstructor CourseRepository. All we need to do is inject our StoreContext here — let's simply call it context. This time, we need to use quick fix on the context and initialize the field from parameter.
Now all we need to do is to use the context the same way we did in our controllers. Since we're using an asynchronous function, let's write async keyword to our method. Now we need to return
await context.Courses.FindAsync and we will provide the id as a parameter. Let's do the same thing in the second method — provide async keyword, return
await context.Courses.ToListAsync. We need to use quick fix to import
Microsoft.EntityFrameworkCore. This looks good now.
Let's go back to our Courses controller and use the repository instead of StoreContext. Let's take this off and the context off. Now replace StoreContext with ICourseRepository and let us call it repository. Let's import it using quick fix. Again, let's use repository to initialize field from parameter.