46 lines
1.6 KiB
C#
46 lines
1.6 KiB
C#
// using System;
|
|
// using System.Collections.Generic;
|
|
// using System.Linq;
|
|
// using System.Linq.Expressions;
|
|
// using System.Reflection;
|
|
// using System.Threading.Tasks;
|
|
// using Contracts.DTOs.Generic;
|
|
// using Microsoft.EntityFrameworkCore;
|
|
|
|
// namespace Commerce.Core.Utility;
|
|
|
|
// public static class SortExt
|
|
// {
|
|
// public static IQueryable<T> ApplySort<T>(this IQueryable<T> query, SortModel sortModel)
|
|
// {
|
|
// if (string.IsNullOrWhiteSpace(sortModel?.SortBy))
|
|
// return query;
|
|
|
|
// // Get the property info
|
|
// var propertyInfo = typeof(T).GetProperty(
|
|
// sortModel.SortBy,
|
|
// BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance
|
|
// );
|
|
|
|
// if (propertyInfo == null)
|
|
// throw new ArgumentException(
|
|
// $"No property '{sortModel.SortBy}' on type '{typeof(T).Name}'"
|
|
// );
|
|
|
|
// // Create x => x.PropertyName
|
|
// var parameter = Expression.Parameter(typeof(T), "x");
|
|
// var property = Expression.Property(parameter, propertyInfo);
|
|
// var lambda = Expression.Lambda(property, parameter);
|
|
|
|
// // Call OrderBy or OrderByDescending dynamically
|
|
// string methodName = sortModel.SortBy?.ToLower() == "desc" ? "OrderByDescending" : "OrderBy";
|
|
// var result = typeof(Queryable)
|
|
// .GetMethods()
|
|
// .First(m => m.Name == methodName && m.GetParameters().Length == 2)
|
|
// .MakeGenericMethod(typeof(T), propertyInfo.PropertyType)
|
|
// .Invoke(null, new object[] { query, lambda });
|
|
|
|
// return (IQueryable<T>)result;
|
|
// }
|
|
// }
|