[英]Generic repository with generic Id - how to retrieve when int
I have a generic repository that is the base class for all repositories in my project.我有一个通用存储库,它是我项目中所有存储库的基类。 The repository has generic support for the primary key, so it's not necessarily an
int
.存储库对主键有通用支持,因此它不一定是
int
。
My initial implementation was this, to retrieve an object by ID:我最初的实现是这样的,通过 ID 检索一个对象:
return Context.Set<TDomainObject>().Where(x => x.Id.Equals(id)).SingleOrDefaultAsync();
Where Id
is type TPrimaryKey
.其中
Id
是类型TPrimaryKey
。 When I attempt to use this logic for an int
, I get a NotSupportedException
with the message当我尝试将此逻辑用于
int
,我收到一个NotSupportedException
消息
Unable to create a constant value of type 'System.Object'.
无法创建类型为“System.Object”的常量值。 Only primitive types or enumeration types are supported in this context`.
此上下文中仅支持原始类型或枚举类型。
So I thought I'd be clever, and special case where TPrimaryKey
is int
and do the evaluation like so:所以我想我会很聪明,在
TPrimaryKey
是int
特殊情况下,像这样进行评估:
if (typeof(TPrimaryKey) == typeof(int))
{
int iId = (int)(object)id;
return Context.Set<TDomainObject>().Where(x => ((int)(object)x.Id) == iId).SingleOrDefaultAsync();
}
This yields a different exception:这会产生一个不同的异常:
Unable to cast the type 'System.Int32' to type 'System.Object'.
无法将“System.Int32”类型转换为“System.Object”类型。 LINQ to Entities only supports casting EDM primitive or enumeration types.`
LINQ to Entities 仅支持转换 EDM 原语或枚举类型。`
How can I make my generic repository work with ints?如何让我的通用存储库与整数一起工作?
您可以使用Find方法
return Context.Set<TDomainObject>().Find(id);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.