c# - 使用 Entity Framework Core 实现通用 GetByIds()
问题描述
我想创建一个通用方法GetByIds()
。我尝试使用这样的东西:How to implement generic GetById() where Id can be of various types
但这对我不起作用。在数据库中,我将主键存储为 long 和 int。
我有这个通用方法:
public async virtual Task<List<TValue>> GetAsync<TKey, TValue>(ICollection<TKey> id)
where TKey : struct
where TValue : class, IReferenceType<TKey, TValue>
{
// Here I get an error:
// Operator '==' cannot be applied to operands of type 'TKey' and 'TKey'
List<TValue> items = await _dataContextCORE
.Set<TValue>()
.Where(w => id.Any(x => x == w.GetReferenceKey()))
.ToListAsync();
return items;
}
参考类型:
public interface IReferenceType<TKey, TValue>
where TKey : struct
where TValue : class
{
TKey GetReferenceKey();
TValue GetReferenceValue();
}
GetReferenceKey()
从课堂返回Id
(PK)。
我不能使用x == w.GetReferenceKey()
所以我尝试了Equals
,Contains
但是当我尝试获取数据时出现错误:
无法翻译 LINQ 表达式 'DbSet() .Where(o => __id_0 .Any(x => x.Equals((object)o.GetReferenceKey())))'。以可翻译的形式重写查询,或通过插入对“AsEnumerable”、“AsAsyncEnumerable”、“ToList”或“ToListAsync”的调用显式切换到客户端评估。
是否可以为我的任务创建这种通用方法?
解决方案
推荐阅读
- facebook - 在 Facebook 浏览器中更新 Service Worker
- azure - 获取受保护的 Azure ADv2 Rest Api 的令牌
- apache-spark - Spark 数据框将配置单元结构类型读取为数组而不是映射
- amazon-dynamodb - 如何将所有唯一的非键列记录从 DynamoDB 表转移到另一个新表?
- apache-spark - 即使在 spark-defaults 中设置,也无法更改 spark.driver.memory
- python - 如何在处理文本时忽略带有熊猫的 CSV 列中的 Null 值?
- android - 如何将 OPEN_APP_FEATURE 操作集成到 Android 应用程序中?
- c# - Ajax Post 将 null 传递给控制器
- react-native - 无法运行 react-native 项目
- google-bigquery - 在 bigquery 中的两个表上具有阈值的 SUM 聚合