[英]Filter a DbSet by the content of an IList using LINQ
我有 2 個 ILists 供應商和 VwSrmAhmSuppliers。 它們都是從數據庫中查詢的。 我先填寫供應商。 然后,當我查詢 VwSrmAhmSuppliers 時,我想根據我已經在供應商中提取的內容過濾結果。
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 。
我不清楚。
您需要首先投影出簡單引用類型( int
、 string
等)的內存中集合,而不是類型Supplier
的列表,然后將其用於您的Any
或Contains
條件,例如:
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.