Error with skip and take in child entity using projection with EF Core

Viewed 352

I have this query below and I'm getting these 2 errors from the Members property

Error: An exception occurred while iterating over the results of a query for context type 'Infrastructure.Data.DataContext'.

Invalid column name 'UserId' Invalid column name 'Status'

If I remove the Skip() and Take() the query will run! If I remove the .select() projection the query will run!

I tried placing the skip/take before the .select() but it still gave me the error.

I also tried removing .ToList(), but still got the error as well.

var yogabandTest = await _dbContext.Yogabands
.Select(p => new
{
    Id = p.Id,
    Name = p.Name,
    HostId = p.HostId,
    MemberCount = p.Members.Count(),
    Members = p.Members
        .Where(p => p.Status == YogabandMemberStatus.Active)
        .OrderByDescending(p => p.Status)
        .Select(p => new {
            Id = p.User.Id,
            Name = p.User.UserName,
        })
        .Skip(0)
        .Take(1)
        .ToList()    
})
.FirstOrDefaultAsync(p => p.Name == pageParams.YogabandName && p.HostId == hostId);

UPDATE - I've rewritten the query with an .Include() using this MS link and now the query runs, BUT it doesn't Take() the number I provide ex. (2). It just returns all rows (5) in the .Members result.

var yogabandTest = await _dbContext.Yogabands
            .Include(
                yogaband => yogaband.Members
                    .Where(member => member.Status == YogabandMemberStatus.Active)
                    .OrderByDescending(member => member.Status)
                    .Skip(0)
                    .Take(2)
            )
            .Select(p => new
            {
                Id = p.Id,
                Name = p.Name,
                HostId = p.HostId,
                Members = p.Members
                    .Select(p => new {
                        Id = p.User.Id,
                        Name = p.User.UserName
                    })
                    
            })
            .FirstOrDefaultAsync(p => p.Name == pageParams.YogabandName && p.HostId == hostId);
0 Answers
Related