Error when using Select() instead of Include() in a query

I have the following query:

var catInclude = _db.Cat
    .Where(x => x.ProvId == request.ProvId)
    .Include(x => x.CatItems)
    .SingleOrDefault(p => p.Id == request.ProvId
         cancellationToken: cancellationToken);

As I don't want to get all properties from CatItems with Include(), I have created the following query:

var catSelect = _db.Cat
.Where(x => x.ProvId == request.ProvId)
.Select(p ==> new
    { Provider = p,
      Items = p.CatItems.Select(x => new List<CatItems> { new CatItems
{ Id = x.Id, Name = x.Name, Price = x.Price } }
})})
SingleOrDefault(cancellationToken: cancellationToken);

But something is wrong in the 2nd query because here return _mapper.ProjectTo<CatDto>(cat) I get the following error:

Argument 1: cannot convert from '<anonymous type: Db.Entities.Cat Prov, System.Colletions.Generic.IEnumerable<System.Colletions.Generic.List<Models.CatItems> > Items>' to 'System.Linq.IQueryable'

Here is my CatDto:

public class CatDto
{
   public int ProvId { get; set; }
   public List<CatItems> CatItems { get; set; }
}

Here are my entities:

public class Prov
{
   public int Id { get; set; }
   public Cat Cat { get; set; }
}

public class Cat
{
   public int Id { get; set; }
   public int ProvId { get; set; }
   public List<CatItems> CatItems { get; set; }
}

public class CatItems
{
   public int Id { get; set; }
   public int CatId { get; set; }
   public DateTime CreatedOn { get; set; }
}

Is there a way to recreate the 2nd query and use it?


Solution 1:

Main difference that instead of returning List of CatItems, your code returns IEnumerable<List<CatItems>> for property Items.

So, just correct your query to project to List:

var catSelect = await _db.Cat
    .Where(x => x.ProvId == request.ProvId)
    .Select(p => new CatDto
    { 
        ProvId = p.ProvId,
        Items = p.CatItems.Select(x => new CatItems
        { 
            Id = x.Id, 
            Name = x.Name, 
            Price = x.Price 
        })
        .ToList()
    })
    .SingleOrDefaultAsync(cancellationToken: cancellationToken);