通用 T GetByID(K ID_)
我正在尝试使用实体框架实现通用存储库。
我的存储库定义为:
public class GenericRepository<T> : IRepository<T> where T : class
我想添加一个通用 GetByID,其中传入的 ID 类型也是通用的。我真的不希望我的业务逻辑告诉我类型是例如...
_repository.GetByID<int>(123);
我想隐藏 tyoe 定义,但无法弄清楚在哪里或如何执行此操作。
Stackoverflow 上的大多数帖子似乎都将 ID 设为整数。我不希望这样,因为你的标识符并不总是整数!
关于这个问题有什么想法吗?
I'm trying to implement a generic repository using the entity framework.
My repository is defined as :
public class GenericRepository<T> : IRepository<T> where T : class
I want to add a generic GetByID where the type of ID being passed in is generic too. I don't really want my business logic to tell me the type is e.g....
_repository.GetByID<int>(123);
I want to hide the tyoe definition but can't figure out where or how to do this.
Most posts on Stackoverflow seem to just have their ID's as ints. I don't want this as your identifiers aren't always going to be ints!
Any ideas on this issue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我这样做了
然后我继承了这个接口
这使得它对 DI/IoC 和单元测试也非常友好。
I did this
Then I inherit from this interface
This makes it very DI/IoC and Unit Testing friendly too.
我已在我的
IRepository
中将 ID 定义为object
。有时是int
,有时是Guid
,有时是string
。虽然不是最优的,但它确实有效。
I have defined ID as
object
in myIRepository
. Sometimes it isint
, sometimesGuid
and sometimesstring
.It is sub-optimal but it works.
您可以将方法定义为接受类型:
var t = new Thing();
t.GetById(44);
其中
You can define a method as accepting a type:
var t = new Thing();
t.GetById<int>(44);
where
您是否尝试过超载?:
Have you tried overloading?: