C# 实现通用存储库模式-实体键类型
我正在Asp.NETWebAPI应用程序中实现一个存储库模式C# 实现通用存储库模式-实体键类型,c#,entity-framework,generics,asp.net-web-api2,repository-pattern,C#,Entity Framework,Generics,Asp.net Web Api2,Repository Pattern,我正在Asp.NETWebAPI应用程序中实现一个存储库模式 public abstract class Repository<T> : IRepository<T> where T : EntityBase { private DbContext context_; public Repository(DbContext context) { context_ = context; } publi
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);
}
...
}
公共抽象类存储库:IRepository其中T:EntityBase
{
私有DbContext上下文;
公共存储库(DbContext上下文)
{
上下文=上下文;
}
公共虚拟异步任务GetAsync(int id)
{
返回wait context_uz.Set().FindAsync(id);
}
...
}
问题:
这里我有一个方法GetAsync(int-id)
,它将用于实体,该实体有一个int
类型的单键
但有些实体的键为string
类型,有些实体的键为复合键
问题:
我如何克服这个问题
有没有可能用一种通用的方法解决这个问题?您可以注意到
FindAsync
接受对象数组作为参数,因此您可以像这样更改GetAsync
:
public virtual Task<T> GetAsync(params object[] keys)
{
return context_.Set<T>().FindAsync(keys);
}
旁注:实体框架
Set
已经是通用存储库,因此在该存储库上添加另一个存储库并不会带来太多好处。谢谢!我没有注意到params对象[]键
GetAsync(1);
GetAsync("string key");
GetAsync(1, "composite key");