Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing Generic Repository Pattern - entity key type

I'm implementing a repository pattern in Asp.Net web api application.

public abstract class Repository<T> : IRepository<T> where T : EntityBase
 {
     private DbContext context_;

     public Repository(DbContext context)
     {
         context_ = context;
     }

     public virtual async Task<T> GetAsync(int id)
     {
         return await context_.Set<T>().FindAsync(id);
     }

     ...

 }

Problem:

Here I have a method GetAsync(int id), which will work for entity which has a single key with int type.

But there are some entity with key of string type and some entities with composite keys.

Question:

How can I overcome this issue?

Is it possible to overcome the issue in a generic way?

like image 240
Rahul Avatar asked Mar 09 '23 11:03

Rahul


1 Answers

You can notice that FindAsync accepts array of objects as a parameter, so you can change your GetAsync like this:

public virtual Task<T> GetAsync(params object[] keys)
{
     return context_.Set<T>().FindAsync(keys);
}

Then you are able to call GetAsync with any keys you like, for example:

GetAsync(1);
GetAsync("string key");
GetAsync(1, "composite key");

Side note: entity framework Set<T> is already generic repository, so adding another repository over that one does not really add much benefits.

like image 176
Evk Avatar answered Mar 23 '23 10:03

Evk