[英]Implementing Generic Repository Pattern - entity key type
I'm implementing a repository pattern in Asp.Net web api application. 我正在Asp.Net web api应用程序中实现一个存储库模式。
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. 这里我有一个方法
GetAsync(int id)
,它适用于具有int
类型的单个键的实体。
But there are some entity with key of string
type and some entities with composite keys. 但是有一些实体具有
string
类型的键和一些具有复合键的实体。
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: 您可以注意到
FindAsync
接受对象数组作为参数,因此您可以像这样更改GetAsync
:
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
,例如:
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. 附注:实体框架
Set<T>
已经是通用存储库,因此在该存储库上添加另一个存储库并不会带来太多好处。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.