MrMustafa
MrMustafa

Reputation: 305

Using Expression Tree in LINQ to Entity Framework Core

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)

Upvotes: 0

Views: 841

Answers (1)

Camilo Terevinto
Camilo Terevinto

Reputation: 32072

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();

Upvotes: 1

Related Questions