Why EF Core LINQ query works okay for one child and does not work for another one?

So I have a query to get a list of chats with 2 users (including their pictures) and the last message.

An exception is thrown because of that last message sub-query:

“The LINQ expression ‘ROW_NUMBER() OVER(PARTITION BY p5.P2pChatId
ORDER BY p5.CreatedOn DESC)’ 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.”

LastMessage = x.P2pChatMessages
             .OrderByDescending(y => y.CreatedOn)
             .Select(y => new P2pChatMessageViewModel()
             {
                 Id = y.Id,
                 ChatId = y.P2pChatId,
                 UserId = y.UserId,
                 CreatedOn = y.CreatedOn.ToString("s") + "+00:00",
                 Text = y.Text,
             })
             .FirstOrDefault()

My question is why this sub-query fails, while the same sub-query right above passes ok:

Person2 = x.Person2 == null ? null : new UserViewModel()
             {
                 Id = x.Person2.Id,
                 Username = x.Person2.UserName,
                 Email = x.Person2.Email,
                 ProfilePicture = new ImageViewModel()
                 {
                     UserId = x.Person2.Id,
                     Url = x.Person2.ProfilePictures.OrderByDescending(y => y.CreatedOn).Select(y => y.Image.Url).FirstOrDefault(),
                     Id = x.Person2.ProfilePictures.OrderByDescending(y => y.CreatedOn).Select(y => y.Image.Id).FirstOrDefault(),
                 },
             },

Full query:

 var list = await _db.P2pChats
     .OrderByDescending(x => x.P2pChatMessages.Any(y => !y.IsRead))
     .Select(x => new P2pChatViewModel
     {
         Id = x.Id,
         Person1 = x.Person1 == null ? null : new UserViewModel()
         {
             Id = x.Person1.Id,
             Username = x.Person1.UserName,
             Email = x.Person1.Email,
             ProfilePicture = new ImageViewModel()
             {
                 UserId = x.Person1.Id,
                 Url = x.Person1.ProfilePictures.OrderByDescending(y => y.CreatedOn).Select(y => y.Image.Url).FirstOrDefault(),
                 Id = x.Person1.ProfilePictures.OrderByDescending(y => y.CreatedOn).Select(y => y.Image.Id).FirstOrDefault(),
             },
         },
         Person2 = x.Person2 == null ? null : new UserViewModel()
         {
             Id = x.Person2.Id,
             Username = x.Person2.UserName,
             Email = x.Person2.Email,
             ProfilePicture = new ImageViewModel()
             {
                 UserId = x.Person2.Id,
                 Url = x.Person2.ProfilePictures.OrderByDescending(y => y.CreatedOn).Select(y => y.Image.Url).FirstOrDefault(),
                 Id = x.Person2.ProfilePictures.OrderByDescending(y => y.CreatedOn).Select(y => y.Image.Id).FirstOrDefault(),
             },
         },
         LastMessage = x.P2pChatMessages
             .OrderByDescending(y => y.CreatedOn)
             .Select(y => new P2pChatMessageViewModel()
                 {
                     Id = y.Id,
                     ChatId = y.P2pChatId,
                     UserId = y.UserId,
                     CreatedOn = y.CreatedOn.ToString("s") + "+00:00",
                     Text = y.Text,
                 })
             .FirstOrDefault()
         })
     .Take(50)
     .ToListAsync();

4

The problem is that you have a client-side evaluation in CreatedOn, and this is being placed before the ROW_NUMBER transform.

You can solve this by either changing to a server-side evaluation. For this you would need to add the CONVERT function to your model as a DbFunction, then call it:

CreatedOn = MyFunctions.Convert(y.CreatedOn, 126) + "+00:00",

Or push the row-number to earlier in the query before client-side evaluation, by using an intermediate variable

var list = await _db.P2pChats
     .OrderByDescending(x => x.P2pChatMessages.Any(y => !y.IsRead))
     .Select(x => new {
         x,
         LastMessage = x.P2pChatMessages.OrderByDescending(y => y.CreatedOn).FirstOrDefault()
     })
     .Select(x => new P2pChatViewModel
     {
         Id = x.x.Id,
         Person1 = x.x.Person1 == null ? null : new UserViewModel()
         {
             Id = x.x.Person1.Id,
             Username = x.x.Person1.UserName,
             Email = x.x.Person1.Email,
             ProfilePicture = new ImageViewModel()
             {
                 UserId = x.x.Person1.Id,
                 Url = x.x.Person1.ProfilePictures.OrderByDescending(y => y.CreatedOn).Select(y => y.Image.Url).FirstOrDefault(),
                 Id = x.x.Person1.ProfilePictures.OrderByDescending(y => y.CreatedOn).Select(y => y.Image.Id).FirstOrDefault(),
             },
         },
         Person2 = x.x.Person2 == null ? null : new UserViewModel()
         {
             Id = x.x.Person2.Id,
             Username = x.x.Person2.UserName,
             Email = x.x.Person2.Email,
             ProfilePicture = new ImageViewModel()
             {
                 UserId = x.x.Person2.Id,
                 Url = x.x.Person2.ProfilePictures.OrderByDescending(y => y.CreatedOn).Select(y => y.x.Image.Url).FirstOrDefault(),
                 Id = x.x.Person2.ProfilePictures.OrderByDescending(y => y.CreatedOn).Select(y => y.Image.Id).FirstOrDefault(),
             },
         },
         LastMessage = new P2pChatMessageViewModel
         {
             Id = x.LastMessage.Id,
             ChatId = x.LastMessage.P2pChatId,
             UserId = x.LastMessage.UserId,
             CreatedOn = x.LastMessage.CreatedOn.ToString("s") + "+00:00",
             Text = x.LastMessage.Text,
          })
     })
     .Take(50)
     .ToListAsync();

However, I strongly suspect that this query can be written much better anyway, by combining and moving the duplicate subqueries into variables. This is often easier in Query Syntax rather than Method Syntax, because you can use let.

var list = await
    from c in _db.P2pChats
    let cm = c.P2pChatMessages
        .GroupBy(c => 1)  // group by empty set
        .Select(g => new {
            AnyUnread = g.Where(y => !y.IsRead).Any(),
            LastMessage = g.OrderByDescending(y => y.CreatedOn).FirstOrDefault(),
        })
    let ppImage1 = c.Person1?.ProfilePictures.OrderByDescending(y => y.CreatedOn).Select(y => y.Image).FirstOrDefault()
    let ppImage2 = c.Person2?.ProfilePictures.OrderByDescending(y => y.CreatedOn).Select(y => y.Image).FirstOrDefault()
    orderby cm.AnyUnread descending
    select new P2pChatViewModel
    {
        Id = c.Id,
        Person1 = c.Person1 == null ? null : new UserViewModel()
        {
            Id = c.Person1.Id,
            Username = c.Person1.UserName,
            Email = c.Person1.Email,
            ProfilePicture = new ImageViewModel()
            {
                UserId = c.Person1.Id,
                Url = ppImage1.Url,
                Id = ppImage1.Id,
            },
        },
        Person2 = c.Person2 == null ? null : new UserViewModel()
        {
            Id = c.Person2.Id,
            Username = c.Person2.UserName,
            Email = c.Person2.Email,
            ProfilePicture = new ImageViewModel()
            {
                UserId = c.Person2.Id,
                Url = ppImage2.Url,
                Id = ppImage2.Id,
            },
        },
        LastMessage = cm.LastMessage,
     .Take(50)
     .ToListAsync();

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật