簡體   English   中英

左連接中帶有子查詢的 LINQ 查詢出錯

[英]Error on LINQ query with sub query in left join

我正在嘗試使用 LINQ 在左聯接內執行子查詢,在 SQL 中看起來像這樣:

SELECT fields
FROM table1 A
LEFT JOIN table2 B ON B.Establishment = A.Establishment  
LEFT JOIN table3 C ON C.Vdb = B.Vdb AND C.Year = (SELECT MAX(Year) FROM table3 D WHERE D.Vdb = C.Vdb)

使用 LINQ,我做了以下事情:

var query = await (
    from a in _context.Table1
    
    join b in _context.Table2 on a.Establishment equals b.Establishment
    
    join c0 in _context.Table3 on b.Vdb equals c0.Vdb into gGroup
    from c in gGroup.Where(x => x.Year == (from c1 in _context.Table3
                                            where c1.Vdb == x.Vdb
                                            select c1.Year).Max()).DefaultIfEmpty()
                                            
    select new
    {
        fields
    })
    .ToListAsync();

我使用 LINQPad 構建了這段代碼,所以我嘗試在那里運行並且一切正常,但是當我將這段代碼放入我的 IDE 並嘗試運行它時,我收到以下錯誤:

{
  "Message": "The LINQ expression (expression here) could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.",
  "ErrorName": "InvalidOperationException"
}

所以我不知道到底出了什么問題所以我可以解決這個問題,任何人都可以幫助我嗎?

EF Core 幾乎無法翻譯GroupJoin 如果您不執行簡單的 LEFT JOIN,請不要使用此運算符。

我重寫了查詢以使用另一種返回相同結果的技術:

var table3 = _context.Table3;

var latest = 
    from t in table3.Select(t => new { t.Vdb }).Distinct()
    from r in table3
      .Where(r => r.Vdb == t.Vdb)
      .OrderByDescending(r.Year)
      .Take(1)
    select r;

var query = 
    from a in _context.Table1
    join b in _context.Table2 on a.Establishment equals b.Establishment into gb
    from b in gb.DefaultIfEmpty()
    join c in latest on b.Vdb equals c.Vdb into gc
    from c in gc.DefaultIfEmpty()
    select new
    {
        // fields
    };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM