首页 > 解决方案 > 使用 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()所以我尝试了EqualsContains但是当我尝试获取数据时出现错误:

无法翻译 LINQ 表达式 'DbSet() .Where(o => __id_0 .Any(x => x.Equals((object)o.GetReferenceKey())))'。以可翻译的形式重写查询,或通过插入对“AsEnumerable”、“AsAsyncEnumerable”、“ToList”或“ToListAsync”的调用显式切换到客户端评估。

是否可以为我的任务创建这种通用方法?

标签: c#entity-framework-core.net-5

解决方案


推荐阅读