1

I'm trying to use new EF Core Shadow Property for server side pagination, sorting and filtering of a list results.

Sorting and pagination working great except of when I want to sort column by entity child property UserName. Is there a way to use shadow property to sort by the property child property?
Something like this: .OrderBy(p => EF.Property<object>(p, "user.UserName"))

Entity Model:

public class Player
{
    public int Id { get; set; }
    public int UserId { get; set; }
    public int GamePlayed { get; set; }
    public int GameWon { get; set; }
    public int Rank { get; set; }
    public DateTime LastPlayedDate { get; set; }
    public DateTime JoinDate { get; set; }
    public bool Active { get; set; }
    public virtual User User { get; set; }
}

public class User
{
    public int Id { get; set; }
    public string UserName { get; set; }
    public string Email { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Description { get; set; }
}

Query:

public IEnumerable<Player> GetPlayers(string colName, string filter,
        string sortOrder, int pageNumber, int pageSize)
    {
        var skip = pageNumber * pageSize;

        var results = (sortOrder == "asc") ?
            _context.Players.Where(p => p.Active)
            .OrderBy(p => EF.Property<object>(p, colName))
            .Skip(skip).Take(pageSize)
            .Include(p => p.User)
            :
            _context.Players.Where(p => p.Active)
            .OrderByDescending(p => EF.Property<object>(p, colName))
            .Skip(skip).Take(pageSize)
            .Include(p => p.User);

        return results;
    }
Whistler
  • 1,897
  • 4
  • 29
  • 50
  • 1
    Negative. Use this extension https://stackoverflow.com/questions/39908403/how-to-use-a-string-to-create-a-ef-order-by-expression/39916384#39916384 or similar. – Ivan Stoev Jan 29 '19 at 13:49
  • 1
    Thank you, exactly what I need it. If you add it as answer I will mark it for you. – Whistler Jan 29 '19 at 19:16

0 Answers0