Files
zszq-trs/YLErpDAL/BLL_System/BLLExtension.cs
T
2024-05-09 14:06:26 +08:00

71 lines
2.5 KiB
C#

using System.Linq.Expressions;
namespace BaseOUDAL
{
public static class BllExtension
{
public static SearchListResult<T> ToSearchList<T>(this IQueryable<T> query, BaseSearchReq req, bool isWithOrder = true)
{
if (req.rows == 0)
{
req.rows = 100000;
req.page = 1;
}
if (req.page <= 0)
{
req.page = 1;
}
if (isWithOrder)
{
if (req.sidx != null)
{
var sidx = req.sidx.Split(',').ToList();
var anotherLevel = false;
sidx.ForEach(t =>
{
query = OrderingHelper<T>(query, t.Trim(), req.sord == "desc", anotherLevel);
anotherLevel = true;
});
}
}
var retListResult = new SearchListResult<T>
{
records = query.Count(),
rows = query.Skip((req.page - 1) * req.rows).Take(req.rows).ToList(),
page = req.page
};
retListResult.total = (retListResult.records - 1) / req.rows + 1;
return retListResult;
}
static IOrderedQueryable<T> OrderingHelper<T>(IQueryable<T> source, string propertyName, bool descending, bool anotherLevel)
{
var param = Expression.Parameter(typeof(T), string.Empty); // I don't care about some naming
var propNameArray = propertyName.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
MemberExpression property = null;
foreach (var propName in propNameArray)
{
if (property == null)
{
property = Expression.PropertyOrField(param, propName);
}
else
{
property = Expression.PropertyOrField(property, propName);
}
}
var sort = Expression.Lambda(property, param);
var call = Expression.Call(
typeof(Queryable),
(!anotherLevel ? "OrderBy" : "ThenBy") + (descending ? "Descending" : string.Empty),
new[] { typeof(T), property.Type },
source.Expression,
Expression.Quote(sort));
return (IOrderedQueryable<T>)source.Provider.CreateQuery<T>(call);
}
}
}