我正在尝试使用实体框架实现通用存储库。
我的存储库定义为:
public class GenericRepository<T> : IRepository<T> where T : class
我想添加一个泛型getbyid,其中传入的id类型也是泛型的。我不想让我的业务逻辑告诉我类型是例如…
_repository.GetByID<int>(123);
我想隐藏tyoe的定义,但不知道在哪里或如何做到这一点。
stackoverflow上的大多数帖子的id都是int。我不想这样,因为你的标识符不总是int!
关于这个问题有什么想法吗?
最佳答案
我做到了
interface IRepository<TEntity, TKey> {
TEntity GetById(TKey id);
}
然后我从这个接口继承
class Person {
int ID;
}
interface IPersonRepository : IRepository<Person, int> { ... }
这使得它对di/ioc和单元测试也非常友好。