gpt4 book ai didi

c# - 具有通用 Id 的通用存储库 - 如何在 int 时检索

转载 作者:太空宇宙 更新时间:2023-11-03 10:28:15 25 4
gpt4 key购买 nike

我有一个通用存储库,它是我项目中所有存储库的基类。存储库具有对主键的通用支持,因此它不一定是 int

我最初的实现是这样的,通过 ID 检索对象:

return Context.Set<TDomainObject>().Where(x => x.Id.Equals(id)).SingleOrDefaultAsync();

其中 Id 是类型 TPrimaryKey。当我尝试将此逻辑用于 int 时,我得到一个带有消息的 NotSupportedException

Unable to create a constant value of type 'System.Object'. Only primitive types or enumeration types are supported in this context`.

所以我想我会很聪明,在特殊情况下 TPrimaryKeyint 并像这样进行评估:

if (typeof(TPrimaryKey) == typeof(int))
{
int iId = (int)(object)id;
return Context.Set<TDomainObject>().Where(x => ((int)(object)x.Id) == iId).SingleOrDefaultAsync();
}

这会产生一个不同的异常:

Unable to cast the type 'System.Int32' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types.`

如何让我的通用存储库使用整数?

最佳答案

您可以使用 Find方法

return Context.Set<TDomainObject>().Find(id);

关于c# - 具有通用 Id 的通用存储库 - 如何在 int 时检索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31047433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com