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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With