【问题标题】:Filter a DbSet by the content of an IList using LINQ使用 LINQ 按 IList 的内容过滤 DbSet
【发布时间】:2020-07-01 15:35:29
【问题描述】:

我有 2 个 IList 供应商和 VwSrmAhmSuppliers。它们都是从数据库中查询的。我首先填写供应商。然后,当我查询 VwSrmAhmSuppliers 时,我想根据我已经在 Suppliers 中提取的内容过滤结果。

public IList<Supplier> Suppliers { get;set; }
public IList<Models.ExternalData.VwSrmAhmSupplier> VwSrmAhmSuppliers { get; set; }

public async Task OnGetAsync(Boolean? All)
{
   //don't show all records unless explicity asked to!
   if (All == true)
   {
      Suppliers = await _context.Supplier
         .Include(s => s.Status)
         .Include(c => c.Category)
         .Include(c => c.Comments)
         .OrderByDescending(c => c.CreateDate)
         .ToListAsync();

      //these do not work
      //VwSrmAhmSuppliers = await _externalcontext.VwSrmAhmSuppliers.Where(d => Suppliers.Any(s=>s.SupplierNo == d.AhmSupplierNo)).ToListAsync();
      //VwSrmAhmSuppliers = await _externalcontext.VwSrmAhmSuppliers.Where(v => Suppliers.Any(s=> s.SupplierNo.Equals(v.AhmSupplierNo))).ToListAsync();

      //This does work, it gets all suppliers but it's too many
      //VwSrmAhmSuppliers = await _externalcontext.VwSrmAhmSuppliers.ToListAsync();


      VwSrmAhmSuppliers = await _externalcontext.VwSrmAhmSuppliers
         .Where(v => Suppliers
            .Any(s => s.SupplierNo == v.AhmSupplierNo))
         .ToListAsync();
   }
}

产生的错误是:

InvalidOperationException:LINQ 表达式 'DbSet .Where(v => __Suppliers_0 .Any(s => s.SupplierNo == v.AhmSupplierNo))' 无法翻译。任何一个 以可以翻译的形式重写查询,或切换到 通过插入对任何一个的调用来显式地评估客户 AsEnumerable()、AsAsyncEnumerable()、ToList() 或 ToListAsync()。看 https://go.microsoft.com/fwlink/?linkid=2101038 了解更多信息。

我也不清楚。

【问题讨论】:

  • 您需要先投影出一个 id 列表,而不是 Supplier,然后在您的 AnyContains 条件中使用它。

标签: c# linq asp.net-core razor-pages


【解决方案1】:

您需要先投影出简单引用类型(intstring 等)的内存中集合,而不是 Supplier 类型的列表,然后将其用于您的 Any 或 @ 987654325@条件,例如:

Suppliers = await _context.Supplier
         .Include(s => s.Status)
         .Include(c => c.Category)
         .Include(c => c.Comments)
         .OrderByDescending(c => c.CreateDate)
         .ToListAsync();

//Project out the required references
var supplierNos = Suppliers.Select(s => s.SupplierNo).ToList();

//Use the simple reference type collection in your query
VwSrmAhmSuppliers = await _externalcontext.VwSrmAhmSuppliers
    .Where(d => supplierNos.Any(s=> s == d.AhmSupplierNo)).ToListAsync();

【讨论】:

    猜你喜欢
    • 2021-12-28
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 2018-12-23
    • 2013-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多