using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Reflection;
using System.Text;
namespace Core.Util
{
public static class DbSearchHelper
{
public static List<DbStatisData> GetDbStatisData(this IQueryable dataSource, string groupColumn, string statisColumn, string funcName)
{
List<DbStatisData> resData = new List<DbStatisData>();
var q = dataSource.GroupBy(groupColumn, "it")
.Select($"new (it.Key as Key,{funcName}(it.{statisColumn}) as Value)")
.CastToList<dynamic>();
foreach (dynamic aData in q)
{
DbStatisData newData = new DbStatisData();
resData.Add(newData);
newData.Key = aData.Key;
newData.Value = aData.Value;
}
return resData;
}
public static List<DynamicModel> GetDbStatisData(this IQueryable dataSource, string groupColumn, SearchEntry[] searchEntris)
{
if (searchEntris.Count() == 0)
throw new Exception("请输入至少一个查询配置项");
StringBuilder selectStr = new StringBuilder();
selectStr.Append("new (it.Key as Key");
int count = searchEntris.Count();
searchEntris.ForEach((item, index) => {
string end = "";
if (index == count - 1)
end = ")";
selectStr.Append($",{item.FuncName}(it.{item.StatisColoum}) as {item.ResultName}{end}");
});
List<DynamicModel> resData = new List<DynamicModel>();
var q = dataSource.GroupBy(groupColumn, "it")
.Select(selectStr.ToString())
.CastToList<dynamic>();
foreach (dynamic aData in q)
{
DynamicModel newData = new DynamicModel();
resData.Add(newData);
object obj = (object)aData;
Type type = obj.GetType();
newData.AddProperty("Key", type.GetProperty("Key").GetValue(obj));
searchEntris.ForEach(item =>
{
newData.AddProperty(item.ResultName, type.GetProperty(item.ResultName).GetValue(obj));
});
}
return resData;
}
public static IQueryable GetIQueryable(object obj, string funcName, string entityName, string nameSpace)
{
Type type = obj.GetType();
MethodInfo method = type.GetMethod(funcName);
var entityType = Assembly.Load(nameSpace).GetTypes().Where(x => x.Name.ToLower().Contains(entityName.ToLower())).FirstOrDefault();
if (entityType.IsNullOrEmpty())
throw new Exception("请输入有效的实体名!");
var iQueryable = (IQueryable)method.MakeGenericMethod(entityType).Invoke(obj, null);
return iQueryable;
}
}
public class DbStatisData
{
public string Key { get; set;}
public double? Value { get; set; }
}
public struct SearchEntry
{
public string StatisColoum { get; set; }
public string ResultName { get; set; }
public string FuncName { get; set; }
}
}