我有一个包含 ID 号的对象列表。我想查询数据库中的一个表,以提供 ID 不 与列表中任何对象的 ID 匹配的所有行。
List<Item> allItems = new List<Item>();
// Populate allItems
Item
是一个带有public int ItemID
和public string Name
的简单对象。
这是我尝试查询特定表的 LINQ,它只提供在 allItems
中不作为 ItemID
存在的行:
var filtered = ctx.PurchasedItems.Where(x => allItems.Select(y => y.ItemID).ToList().Contains(x.FK_ItemID)).ToList();
如您所见,dbo.PurchasedItems
有一列 FK_ItemID
与对象 Item 中的 ItemID
匹配。
虽然编译成功了,但运行时出现以下错误:
"Unable to create a constant value of type 'DemoProject.Models.ItemDatabase.PurchasedItems'. Only primitive types or enumeration types are supported in this context."
我尝试的另一种方法是:
var p = ctx.PurchasedItems.Where(x => x.FK_ItemID.IsAnyOf(allItems.Select(y => y.ItemID).ToArray())).ToList();
...但这产生了类似的错误。
谁能帮帮我?
最佳答案
我会重写问题
I have a list (
someItems
) of objects with numeric IDs. I want to query a tablePurchasedItems
in my database to give me all the rows where theFK_ItemID
do not match the ID of any of the objects in my listsomeItems
.
我的回答:
List<Item> someItems = new List<Item>();
// Populate someItems
List<int> someItemIDs = someItems.Select(i=>i.ID).ToList();
var filtered = ctx.PurchasedItems
.Where(x => !someItemIDs.Contains(x.FK_ItemID))
.ToList();
正如@juharr 的评论所指出的,EF 无法处理非基本类型的集合,因为它试图将其转换为 SQL。您可以先创建集合 someItemIDs
。
关于c# - LINQ 查询其中 ID 不作为对象列表中的属性存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54241594/