IQueryableExtensions.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Data.Entity;
  6. using System.Linq.Dynamic;
  7. using System.Linq.Expressions;
  8. using System.Data.Entity.Infrastructure;
  9. //using System.Data.Objects;
  10. using System.Reflection;
  11. using System.Data;
  12. using System.Collections;
  13. using System.Data.Entity.Core.Objects;
  14. using System.Web;
  15. namespace Bowin.Common.Linq.Entity
  16. {
  17. /// <summary>
  18. /// Helper extensions for add IDbSet methods defined only
  19. /// for DbSet and ObjectQuery
  20. /// </summary>
  21. public static class IQueryableExtensions
  22. {
  23. /// <summary>
  24. /// 映射。
  25. /// </summary>
  26. /// <typeparam name="TSource"></typeparam>
  27. /// <param name="queryable"></param>
  28. /// <returns></returns>
  29. public static ExpressionFactory<TSource> Map<TSource>(this IQueryable<TSource> queryable)
  30. {
  31. return new ExpressionFactory<TSource>(queryable);
  32. }
  33. /// <summary>
  34. /// Include extension method for IDbSet
  35. /// <example>
  36. /// var query = ReturnTheQuery();
  37. /// query = query.Include(customer=>customer.Orders);//"Orders"
  38. /// //or
  39. /// query = query.Include(customer=>customer.Orders.Select(o=>o.OrderDetails) //"Orders.OrderDetails"
  40. /// </example>
  41. /// </summary>
  42. /// <typeparam name="TEntity">Type of elements in IQueryable</typeparam>
  43. /// <typeparam name="TEntity">Type of navigated element</typeparam>
  44. /// <param name="queryable">Queryable object</param>
  45. /// <param name="path">Expression with path to include</param>
  46. /// <returns>Queryable object with include path information</returns>
  47. public static IQueryable<TEntity> Include<TEntity, TProperty>(this IDbSet<TEntity> queryable, Expression<Func<TEntity, TProperty>> path)
  48. where TEntity : class
  49. {
  50. var objectQuery = queryable as DbQuery<TEntity>;
  51. if (objectQuery != null) //Is DBSET
  52. {
  53. return objectQuery.Include(path);
  54. }
  55. else // probably mock
  56. return queryable;
  57. }
  58. /// <summary>
  59. /// OfType extension method for IQueryable
  60. /// </summary>
  61. /// <typeparam name="KEntity">The type to filter the elements of the sequence on. </typeparam>
  62. /// <param name="queryable">The queryable object</param>
  63. /// <returns>
  64. /// A new IQueryable hat contains elements from
  65. /// the input sequence of type TResult
  66. /// </returns>
  67. public static IQueryable<KEntity> OfType<TEntity, KEntity>(this IQueryable<TEntity> queryable)
  68. where TEntity : class
  69. where KEntity : class,TEntity
  70. {
  71. var objectQuery = queryable as DbQuery<TEntity>;
  72. if (objectQuery != null) //is DBSET
  73. {
  74. return objectQuery.OfType<KEntity>();
  75. }
  76. else // probably IDbSet Mock
  77. return queryable.OfType<KEntity>();
  78. }
  79. public static IGridResultSet<TEntity> ToGridResultSet<TEntity>(this IQueryable<TEntity> dataSource, int? pageIndex = null, int? pageSize = null)
  80. {
  81. var orderby = (OrderByStatementView)HttpContext.Current.Session["Bowin_Common_Linq_Entity_CurOrderby"];
  82. if (orderby != null)
  83. {
  84. if (orderby.isAsc)
  85. {
  86. dataSource = dataSource.OrderBy(orderby.OrderBy);
  87. }
  88. else
  89. {
  90. dataSource = dataSource.OrderBy(orderby.OrderBy + " desc");
  91. }
  92. HttpContext.Current.Session["Bowin_Common_Linq_Entity_CurOrderby"] = null;
  93. }
  94. if (pageIndex.HasValue && pageSize.HasValue)
  95. {
  96. return new GridResultSet<TEntity>
  97. {
  98. rows = dataSource.Skip(pageIndex.Value * pageSize.Value).Take(pageSize.Value).ToList(),
  99. total = dataSource.Count()
  100. };
  101. }
  102. else
  103. {
  104. var result = new GridResultSet<TEntity>
  105. {
  106. rows = dataSource.ToList()
  107. };
  108. result.total = result.rows.Count;
  109. return result;
  110. }
  111. }
  112. public static IQueryable<TEntity> DynamicWhere<TEntity>(this IQueryable<TEntity> dataSource, string propertyName, string comparer, object value)
  113. {
  114. ExpressionFactory<TEntity> factory = new ExpressionFactory<TEntity>(dataSource);
  115. return dataSource.Where(factory.DynamicExpression(propertyName, comparer, value));
  116. }
  117. public static IQueryable<TEntity> DynamicInWhere<TEntity, TListType>(this IQueryable<TEntity> dataSource, string propertyName, IList<TListType> value)
  118. {
  119. ExpressionFactory<TEntity> factory = new ExpressionFactory<TEntity>(dataSource);
  120. return dataSource.Where(factory.DynamicInExpression(propertyName, value));
  121. }
  122. /// <summary>
  123. /// 分页查询,当 pageIndex 或 pageSize 为null时,获取全部数据。
  124. /// </summary>
  125. /// <typeparam name="TEntity">实体类型</typeparam>
  126. /// <param name="query">分页数据源</param>
  127. /// <param name="pageIndex">页码,从1开始</param>
  128. /// <param name="pageSize">页数</param>
  129. /// <returns></returns>
  130. public static PageList<TEntity> ToPageList<TEntity>(this IQueryable<TEntity> query, int? pageIndex, int? pageSize)
  131. {
  132. return new PageList<TEntity>(query, pageIndex, pageSize);
  133. }
  134. public static ObjectParameterCollection GetParamters<TEntity>(this IQueryable<TEntity> linqBody)
  135. {
  136. var internalQueryField = linqBody.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance).Where(f => f.Name.Equals("_internalSet")).FirstOrDefault();
  137. if (internalQueryField == null)
  138. {
  139. internalQueryField = linqBody.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance).Where(f => f.Name.Equals("_internalQuery")).FirstOrDefault();
  140. }
  141. var internalQuery = internalQueryField.GetValue(linqBody);
  142. var objectQueryField = internalQuery.GetType().GetProperties().Where(f => f.Name.Equals("ObjectQuery")).FirstOrDefault();
  143. var objectQuery = objectQueryField.GetValue(internalQuery, null) as ObjectQuery<TEntity>;
  144. var paras = objectQuery.Parameters;
  145. return paras;
  146. }
  147. public static IDbConnection GetConnection(this IQueryable queryable)
  148. {
  149. var internalQueryField = queryable.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance).Where(f => f.Name.Equals("_internalSet")).FirstOrDefault();
  150. if (internalQueryField == null)
  151. {
  152. internalQueryField = queryable.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance).Where(f => f.Name.Equals("_internalQuery")).FirstOrDefault();
  153. }
  154. var internalQuery = internalQueryField.GetValue(queryable);
  155. var internalContextField = internalQuery.GetType().GetProperties().Where(f => f.Name.Equals("InternalContext")).FirstOrDefault();
  156. var internalContext = internalContextField.GetValue(internalQuery, null);
  157. var internalConnectionField = internalContext.GetType().GetProperties().Where(p => p.Name.Equals("Connection")).FirstOrDefault();
  158. var internalConnection = internalConnectionField.GetValue(internalContext, null);
  159. //var underlyingConnectionProperty = internalConnection.GetType().GetProperties(BindingFlags.NonPublic | BindingFlags.Instance).Where(p => p.Name.Equals("UnderlyingConnection")).FirstOrDefault();
  160. //var underlyingConnection = underlyingConnectionProperty.GetValue(internalConnection, null);
  161. return (IDbConnection)internalConnection;
  162. }
  163. public static string GetConnectionKey(this IQueryable queryable)
  164. {
  165. var internalQueryField = queryable.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance).Where(f => f.Name.Equals("_internalSet")).FirstOrDefault();
  166. if (internalQueryField == null)
  167. {
  168. internalQueryField = queryable.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance).Where(f => f.Name.Equals("_internalQuery")).FirstOrDefault();
  169. }
  170. var internalQuery = internalQueryField.GetValue(queryable);
  171. var internalContextField = internalQuery.GetType().GetProperties().Where(f => f.Name.Equals("InternalContext")).FirstOrDefault();
  172. var internalContext = internalContextField.GetValue(internalQuery, null);
  173. var objectContextProp = internalContext.GetType().GetProperty("ConnectionStringName", BindingFlags.Public | BindingFlags.Instance);
  174. string contextName = objectContextProp.GetValue(internalContext, null).ToString();
  175. return contextName;
  176. }
  177. public static string GetDbConnectionKey(this DbContext db)
  178. {
  179. var internalContextField = typeof(System.Data.Entity.DbContext).GetField("_internalContext", BindingFlags.NonPublic | BindingFlags.Instance);
  180. var internalContext = internalContextField.GetValue(db);
  181. var objectContextProp = internalContext.GetType().GetProperty("ConnectionStringName", BindingFlags.Public | BindingFlags.Instance);
  182. string contextName = objectContextProp.GetValue(internalContext, null).ToString();
  183. return contextName;
  184. }
  185. public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string propertyName, bool ascending) where T : class
  186. {
  187. Type type = typeof(T);
  188. PropertyInfo property = type.GetProperty(propertyName);
  189. if (property == null)
  190. throw new ArgumentException("propertyName", "Not Exist");
  191. ParameterExpression param = Expression.Parameter(type, "p");
  192. Expression propertyAccessExpression = Expression.MakeMemberAccess(param, property);
  193. LambdaExpression orderByExpression = Expression.Lambda(propertyAccessExpression, param);
  194. string methodName = ascending ? "OrderBy" : "OrderByDescending";
  195. MethodCallExpression exp = Expression.Call(
  196. typeof(Queryable)
  197. , methodName
  198. , new Type[] { type, property.PropertyType }
  199. , source.Expression
  200. , Expression.Quote(orderByExpression));
  201. return source.Provider.CreateQuery<T>(exp);
  202. }
  203. /// <summary>
  204. /// 将集合类转换成DataTable
  205. /// </summary>
  206. /// <param name="list">集合</param>
  207. /// <returns></returns>
  208. public static DataTable ToDataTable<T>(this List<T> list)
  209. {
  210. DataTable result = new DataTable();
  211. if (list.Count > 0)
  212. {
  213. PropertyInfo[] propertys = list[0].GetType().GetProperties();
  214. foreach (PropertyInfo pi in propertys)
  215. {
  216. result.Columns.Add(pi.Name, pi.PropertyType);
  217. }
  218. for (int i = 0; i < list.Count; i++)
  219. {
  220. ArrayList tempList = new ArrayList();
  221. foreach (PropertyInfo pi in propertys)
  222. {
  223. object obj = pi.GetValue(list[i], null);
  224. tempList.Add(obj);
  225. }
  226. object[] array = tempList.ToArray();
  227. result.LoadDataRow(array, true);
  228. }
  229. }
  230. return result;
  231. }
  232. }
  233. }