This video is available to students only

Implementing Generic Repository Methods

In this lesson, we're going to implement generic repository methods

Implementing Generic Repository methods#

We've written our generic repository interface and added the service to our startup class. Let's do the implementation of it now. If we look at our other repositories, we know that we want to return a list and an entity, but we also have the include statement to think about. We need to know the type before using the Include statement because we don't know about the navigation properties when we're using generic types. We will focus on it in this section, but for now, let's think about returning the entity individually and in a list.

We can do the implementation now. First of all, we need to inject our Store Context, so let's create a constructor and use our StoreContext which will be called context. We need to initialize field from parameter. Now let's go to the GetIdByAsync method and return await \_context.. This is the place where we want to set the entity that we're going to implement. We don't know it at this time, so we can use the Set method which will set the Dynamic entity in the compile time, Set of type T.FindAsync which will take an id, and of course, we have to make it an asynchronous method. We still see an error because the type T here must be a reference type so we can say type T should be a class, where T is followed by a colon and a class. This means the Dynamic type here must be a class.

Let's implement the second method now. Use async and return await context.Set type t. Now we need to use ToListAsync method; let's import it from Entity framework core. I hope you understand what we're doing here. The type T is dynamic and it will be replaced with the Actual Entity when we will call and use these methods.

Comparing it to the other repositories, we cannot use the Include statement here because we simply don't know the Entity type which means we don't know their navigation properties either. Let's return the main entity first. We will talk about this in future lessons.

Interfaces/GenericRepository

Start a new discussion. All notification go to the author.