gpt4 book ai didi

c# - IQueryable for entities .Where(属性在本地数组中)

转载 作者:太空狗 更新时间:2023-10-29 23:23:18 25 4
gpt4 key购买 nike

所以我知道 iQueryables 被翻译成 SQL 语句,因此无法处理您可能放入 where 子句中的所有可能方法。

但这就是我想要做的:

int[] alreadySelectedIds = ...
var subjects = Entities.NewInstance.Subjects.Where(x => Array.IndexOf(alreadySelectedIds, x.Id) == -1).ToList();

阅读下面这些帖子,我很欣慰 EF5 应该能够翻译它。
Getting Entities whose keys match list(or array) of ids
Using LINQ To Query Int Ids From An Array

但是,我收到了这个错误:

LINQ to Entities does not recognize the method 'Int32 IndexOf[Int32](Int32[], Int32)' method, and this method cannot be translated into a store expression.

用谷歌搜索这个错误并没有给我太多帮助。

我也试过

var newSubjects = Entities.NewInstance.Subjects.Where(x => alreadySelectedIds.Contains(x.Id)).ToList();

Unable to create a null constant value of type 'System.Int32[]'. Only entity types, enumeration types or primitive types are supported in this context.

List<int> alreadySelectedIds = ...

Unable to create a null constant value of type 'System.Collections.Generic.List`1'. Only entity types, enumeration types or primitive types are supported in this context.

我被困住了,我的大脑变得糊涂,无法进行任何类型的优雅恢复。有好心人救救我吗?

最佳答案

Entities.NewInstance.Subjects.Where(x => alreadySelectedIds.Contains(x.Id)).ToList();

应该工作,如果 alreadySelectedIs 不为空

您可以在查询内部或之前进行空检查:

Entities.NewInstance.Subjects.Where(x => alreadySelectedIds == null 
? true // or false
: alreadySelectedIds.Contains(x.Id)
).ToList();

(如果 alreadySelectedIds 为 null,则可以重写,具体取决于您是想要全部还是什么都不想要)

//return all if null
x => alreadySelectedIds == null || alreadySelectedIds.Contains(x.Id)

//return nothing if null
x => alreadySelectedIds != null && alrreadySelectedIds.Contains(x.Id)

关于c# - IQueryable for entities .Where(属性在本地数组中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18618082/

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