假设我有一个包含3个DBSet的DBContext:
我希望编写一个通用方法,实现以下功能:
public class DatabaseContext : DbContext
{
public DbSet<A> As { get; set; }
public DbSet<B> Bs { get; set; }
public DbSet<C> Cs { get; set; }
}
class A
{
public string Text { get; set; }
public string Code { get; set; }
}
class B
{
public string Name { get; set; }
public string Code { get; set; }
}
class C
{
public string Book { get; set; }
public string Code { get; set; }
}
我希望编写一个通用方法,实现以下功能:
- 将三个
DbSet
中的任何一个作为第一个参数进行泛型操作 - 使用字符串值作为第二个参数
- 不需要转换为
IEnumerable
,返回提供的DbSet
中匹配给定字符串的第一条记录中的Code
字段
public static T GetCode<T>(IQueryable<T> set, string code) where T : class
{
var Prop = typeof(T).GetProperty("Code");
return set.Where(x => (string)Prop.GetValue(x) == code).FirstOrDefault();
}
当我尝试使用以下代码行进行调用时:
var _A = GetCode(TheDB.As, "123");
var _B = GetCode(TheDB.Bs, "123");
var _C = GetCode(TheDB.Cs, "123");
我遇到了这个错误:
InvalidOperationException:
无法翻译 LINQ 表达式 'DbSet<A>.Where(m => (string)__Prop_0.GetValue(m) == __code_1)'。
请将查询重写为可翻译的形式,或者通过插入调用 AsEnumerable()、AsAsyncEnumerable()、ToList() 或 ToListAsync() 中的任何一个来明确地切换到客户端评估。
如何编写在 IQueryable
中能够正确翻译的 WHERE
子句?我的方法可以将 IQueryable
强制转换为 IEnumerable
,但我不想这样做,因为集合可能非常大,我希望数据库(而不是我的应用程序)进行记录搜索。