为什么用ef core 3.1 c#解析此表达式会失败?

问题描述 投票:0回答:1

我正在尝试使用此表达式(dbIdGetter):

f => f.FormTemplateId

并在“包含”表达式中使用它:

IEnumerable<ApiEntity> batch = apiEntities.Take(batchSize);
IEnumerable<IdType> batchIds = batch.Select(apiIdGetterCompiled).ToList();

var parameter = Expression.Parameter(typeof(DbEntity), "f");

var batchIdsConst = Expression.Constant(batchIds);
var containsMethod = typeof(List<IdType>).GetMethods().FirstOrDefault(y => y.Name == "Contains");
var body = Expression.Call(Expression.Constant(batchIds), containsMethod, dbIdGetter.Body);

var expr = Expression.Lambda<Func<DbEntity, bool>>(
    body, 
    parameter
);

// Retrieve all the ApiEntity that already exist inside the db to update
IEnumerable<DbEntity> dbBatch = await dbSet.Where(expr).ToListAsync();

“ expr”的调试字符串为:

{f => value(System.Collections.Generic.List`1[System.Int32]).Contains(f.FormTemplateId)}

此电话:

IEnumerable<DbEntity> dbBatch = await dbSet.Where(expr).ToListAsync();

此错误:

System.InvalidOperationException: 'The LINQ expression 'DbSet<SomeClass>
.Where(f => List<int> { 2406369, 2487609, 1997152, 1781014, 2239271, 2256035, 2256334, 2360990, 2256541, 2256652, 2360051, 2256568, 2256600, 2256482, 2256057, 2256088, 2239292, 1934309, }.Contains(f.FormTemplateId))' 

我在做什么错?

c# linq-expressions ef-core-3.1
1个回答
0
投票

谢谢Ivan Stoev,他的评论为我解决了这个问题:

© www.soinside.com 2019 - 2024. All rights reserved.