簡體   English   中英

LINQ 到 NHibernate 加入 - 查詢每組的最新 N - NotSupportedException

[英]LINQ to NHibernate join - Query latest N per group - NotSupportedException

我正在嘗試將最后一條消息發送給每個客戶。 但我得到一個 NotSupportedException 沒有任何額外的細節。 我不熟悉 LINQ 到 NHibernate 的連接方法,因為這是第一次使用它。 有人可以解釋我的查詢有什么問題以及為什么會出現此錯誤嗎? 這是我的查詢和錯誤:

var messages = _session.Query<Communication>();     

return messages.Join(
                _session.Query<Communication>().GroupBy(m => m.Customer),
                x => new { x.Customer, x.Message.CreatedOn },
                g => new { Customer= g.Key, CreatedOn = g.Max(p => p.Message.CreatedOn) },
                (x, g) => x)
                .ToList();

System.NotSupportedException:查詢(查詢(select_from(從(范圍 App.Core.Customer m))(select m)))

實體:

public class Communication
{
    public Message Message { get; set; }
    public Customer Customer { get; set; }
    ...
}

public class Message
{
    public DateTime CreatedOn { get; set; }
    public string Subject { get; set; }
    public string Body { get; set; }
    ...
}

有人可以解釋我的查詢有什么問題以及為什么會出現此錯誤嗎?

NHibernate 不支持子查詢連接。 這給了你NotSupportedException

它也有一些分組子查詢的問題(有關詳細信息,請參閱如何查詢 NHibernate 中每個組中的第一個條目)。 但是使用此答案中描述的最后一種技術,您可以將查詢重寫為:

var results = session.Query<Communication>()
        .Where(c => c == session.Query<Communication>()
                            .Where(cs => cs.Customer == c.Customer)
                            .OrderByDescending(cs => cs.Message.CreatedOn)
                            .First()
        ).ToList();

我假設一個通信就像一個多條消息的線程,並且 CustomerId 存在於通信級別,然后消息有一個 CommunicationId 和一個 CreatedOn。 我不聲稱能夠提供 nHibernate/LINQ 語法,但您也許可以使用原始 SQL 來做到這一點:

var m = _session.CreateSQLQuery(@"

  SELECT m.Id, m.CommunicationId, m.CreatedOn, m.<put a list of all other columns in messages here>
  FROM
    (SELECT *, ROW_NUMBER() OVER(PARTITION BY CommunicationId ORDER BY CreatedOn DESC) rown FROM Messages) m 
  WHERE m.rown = 1")
.AddEntity(typeof(Message))
.List<Message>();

您需要使用 Message 中的所有其他列填寫<... > I think (I've only looked at posts on the web about how to run raw SQL in nH) that this will select all the latest Messages per Communication.. And maybe then crawling round the object tree would be like m.First().Communication.Customer.Name

即希望從這些您可以加入/導航到通信,獲取客戶等。我對原始查詢 nH 知之甚少,不知道如何讓它形成一個 object 圖表,其中包括一次點擊中的通信,但你可以使用這個查詢:

  SELECT d.*
  FROM
    (SELECT *, ROW_NUMBER() OVER(PARTITION BY c.CustomerId ORDER BY CreatedOn DESC) rown FROM Messages m INNER JOIN Communication c ON m.CommunicationId = c.Id) d 
  WHERE d.rown = 1

獲取每個客戶的所有最新消息(如果一個客戶同時有兩個通信,則與每個通信的最新消息略有不同),並將其與此處的建議相結合以使結果動態

也許這就是你想要做的?

return _session
          .Query<Communication>()
          .GroupBy(e => e.Customer)
          .Select(g => new {Customer = g.Key, MaxDate = g.Max(r => r.Message.CreatedOn)})
          .ToList()

暫無
暫無

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

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