Using Expression Tree in LINQ to Entity Framework Core

c# entity-framework-core linq

Question

I want to get data from database ordered by something that i choose it, as example, i want to get all Users registered in website ordered by: Name, Name ascending, Register Date, or Number of comments.

I do not want to repeat all select statement because of only order by statement

that is my code but it not work with me:

Expression<Func<AppUser, Object>> OrderByExpression = null;

switch (userOrder)
{
    case UserOrder.RegistDate:
        OrderByExpression = a => a.RegistrationDate;
        break;
    case UserOrder.A_Z:
        OrderByExpression = a => a.UserName;
        break;
    case UserOrder.Z_A:
        OrderByExpression = a => a.UserName descending;
        break;
    case UserOrder.MostComment:
        OrderByExpression = a => a.Comments.Count;
        break;
}

That is Select statement:

IEnumerable<AppUser> AllUsers = 
    (from a in context.Users
     orderby OrderByExpression.Compile()(a)
     select new AppUser
     {
         UserName = a.UserName,
         Id = a.Id,
         Email = a.Email,
         EmailConfirmed = a.EmailConfirmed,
         RegistrationDate = a.RegistrationDate

     }).ToList();

It work fine but the problem when i want to order by Comments.Count & UserName descending, the problem is in (Count & descending)

1
0
12/17/2017 3:20:23 PM

Accepted Answer

There's a much simpler solution to this, just use the fluent interface of LINQ:

var query = context.Users.AsQueryable();

switch (userOrder)
{
    case UserOrder.RegistDate:
        query = query.Orderby(a => a.RegistrationDate);
        break;
    case UserOrder.A_Z:
        query = query.Orderby(a => a.UserName);
        break;
    case UserOrder.Z_A:
        query = query.OrderbyDescending(a => a.UserName);
        break;
    case UserOrder.MostComment:
        query = query.Orderby(a => a.Comments.Count);
        break;
}

IEnumerable<AppUser> results = query
    .Select(a => new AppUser
    {
        UserName = a.UserName,
        Id = a.Id,
        Email = a.Email,
        EmailConfirmed = a.EmailConfirmed,
        RegistrationDate = a.RegistrationDate
    })
    .ToList();
1
12/17/2017 7:57:15 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow