【问题标题】:Is there a way to avoid foreach with EF Core query有没有办法避免使用 EF Core 查询进行 foreach
【发布时间】:2021-07-24 19:18:26
【问题描述】:

我需要关于 2 件事的建议,以下是 db 模型和代码 1.)使用我的 entityframecore 查询避免 foreach 循环 2.) 在上下文之前使用 await 关键字时出错:- 错误发票模型不可等待

Public abstract class Customer {
Id  ,
Name,
Address , 
Collection <Invoice> Invoices 
}

Public class Invoice 
{
Id,
Date ,
Customer Id ,
Bill Amount
}

我需要账单金额为 500、200、400 的客户名称(账单金额会随着每次请求而变化)

List<string> Customername = new List<string>;

Foreach( var amount in bill amount) {
    Var result =  Context.Invoice
        .Include(Customer) 
        .where( i =>i.billamount == amount) 
        .select ( customer.name); 

     Customername.Add(result) 
}

return Customername; 

PS:- 发帖后格式乱了

【问题讨论】:

  • 为了避免foreach,您可以将Where 谓词替换为(i =&gt; BillAmounts.Contains(i.billamount)),但我不知道这是否会在服务器上或(您可能更喜欢)在数据库作为 SQL。
  • ...或任何真正称为金额的集合

标签: c# entity-framework .net-core entity-framework-core


【解决方案1】:

试试这个

int[] billAmounts= billamount.ToArray(); // {500 , 200, 400 }

return  Context.Invoice
        .Where( i => billAmounts.Contains( i.billamount) )
        .Select (i=> i.Customer.name)
        .ToList();

【讨论】:

    猜你喜欢
    • 2013-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 2019-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多