0

I'm using EF Core 3.0.1 in my project and I need to perform nested projections in sql instead of client-side.

public class Order
{
   public int Id {get;set;}
   public ICollection<Detail> Details {get;set;}
}

public class Detail
{
   public string Comment {get;set;}
}

// Order and Detail has exact same dto's: OrderDto and DetailDto

public PagedCollectionResponse<OrderDto> Execute()
{
   // consider I need to use .Count() somewhere inside this method after applying nested projection.
   var orders = context.Orders
      .Select(x => new OrderDto 
      {
          Id = x.Id,
          Details = x.Details.Select(d => new DetailDto 
          {
              Comment = d.Comment
          })
          // initially, I had no ToList here, but this hasn't fixed the issue
          .ToList();
      });

   var ordersCount = orders.Count(); // works fine, executing only one query in db

   var ordersCount2 = orders.Skip(5).Take(1).Count(); --> System.InvalidCastException: Unable to cast object of type
                                         'Microsoft.EntityFrameworkCore.Query.SqlExpressions.SqlFunctionExpression' to 
                                          type'System.Linq.Expressions.ConstantExpression'
}

However, if I remove collection projection, then both statements assigning counter and counter2 execute normally.

...
.Select(x => new OrderDto 
{
          Id = x.Id
};

var ordersCount = orders.Count(); // OK
var ordersCount2 = orders.Skip(5).Take(1).Count(); // OK

According to the post on EF Core projections I've found, it was a known issue in EF Core 2.0. Was it fixed?

VERSION WARNING (EF Core 2.0.0): At the time of writing nested collection projections only work in memory, defeating the purpose of using them in the first place. This will be fixed soon, so it’s still worth understanding. They DO still work for nested single element projections which we’ll learn about in the next section, so keep reading!

So, is there any known fix on how to make this work?

Maxijuice
  • 1
  • 1
  • Why do you need to select something, if it's just for counting ? :) – Laurent Lequenne Dec 04 '19 at 10:52
  • @LaurentLequenne actually that's a good question. In my case, a custom library is used to handle sorting/filtering/paging, and it requires attributes to be defined on properties, describing whether sorting/filtering is allowed. The idea was not to polute EF entities with those custom attributes, but to define them on the application level models. That's is why I need that projection here – Maxijuice Dec 04 '19 at 11:00
  • Exception type and message indicate EF Core bug. – Ivan Stoev Dec 04 '19 at 12:45
  • Maybe related https://github.com/aspnet/EntityFrameworkCore/issues/18374 – joakimriedel Dec 09 '19 at 07:14

0 Answers0