Linq 查询从 SQL 表(使用 Entity Framework Core)检索与对象 List 列表匹配的数据<BucketList>

问题描述 投票:0回答:1
public class Table1EntityClass
{
    public int id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public decimal Price { get; set; }
    public string Category { get; set; }
    public int Quantity { get; set; }
}

public class BucketList 
{
    public string Name { get; set; }
    public string Price { get; set; }
    public string Category { get; set; }
}

我需要从 table1 获取数据,其中

List<BucketList>
中的名称、价格、类别与存在此组合的行匹配。

例如

'Name- Apple, Description = 'A fruit', Price- 30, category - fruits, Quantity - 10'
'Name- Apple, Description = 'A fruit', Price- 20, category - fruits, Quantity - 10'
'Name- Orange, Description = 'A fruit', Price- 50, category - fruits, Quantity - 10'
'Name- banana, Description = 'A fruit', Price- 30, category - fruits, Quantity - 10'
'Name- Onion, Description = 'A vegetable', Price - 30, category - vegetable, quantity - 5'

List<BucketList>
包含2个对象:

Apple, 30, fruits
Onion, 30, vegetable

方法中的BucketList声明: method declaration

我想接收与表中每个对象列表匹配的数据,即查询应返回第一行和第五行数据。

我尝试了这个查询:

var result = dbContext.table1
                      .Where(item => bucketLists.Any(bucketvalue =>
                                         item.Name == bucketvalue.Name  &&
                                         item.Price == bucketvalue.Price &&
                                         item.Category == bucketvalue.Category))
                      .ToList();

但是我收到一条错误消息,指出 LINQ 查询无法翻译。以可翻译的形式重写查询,或者通过插入对“AsEnumerable”、“AsAsyncEnumerable”、“ToList”或“ToListAsync”的调用来显式切换到客户端评估

还有其他方法可以达到这个目的吗?

c# linq entity-framework-core
1个回答
0
投票

如果

bucketlists
很小,您可以使用
.SelectMany()
单独查询匹配的
table1
行。

var result = bucketLists
    .SelectMany(bucketvalue =>
        dbContext.table1
        .Where(item => item.Name == bucketvalue.Name
                       && item.Price == bucketvalue.Price
                       && item.Category == bucketvalue.Category)
        .Distinct(item => item.itemId)
        .ToList();

虽然这可能会多次访问数据库,但没有“OR”条件应该可以实现更有效的索引使用。 (这假设

table1
(Name, Price, Category)
的某些排列上有一个索引。)

如果

.Distinct()
行可能匹配多个
table1
值,则需要
bucketLists

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