QueryableExtensions.cs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Linq.Expressions;
  5. using System.Reflection;
  6. using System.Text;
  7. using System.Text.RegularExpressions;
  8. using System.Threading.Tasks;
  9. namespace EasyDevCore.Common
  10. {
  11. /// <summary>
  12. /// https://www.devtrends.co.uk/blog/stop-using-automapper-in-your-data-access-code
  13. /// </summary>
  14. public static class QueryableExtensions
  15. {
  16. /// <summary>
  17. /// Projects the specified source.
  18. /// Students.Project().To&lt;StudentAddressDetails&gt;();
  19. /// </summary>
  20. /// <typeparam name="TSource">The type of the source.</typeparam>
  21. /// <param name="source">The source.</param>
  22. /// <returns></returns>
  23. public static ProjectionExpression<TSource> Project<TSource>(this IQueryable<TSource> source)
  24. {
  25. return new ProjectionExpression<TSource>(source);
  26. }
  27. }
  28. /// <summary>
  29. ///
  30. /// </summary>
  31. /// <typeparam name="TSource">The type of the source.</typeparam>
  32. public class ProjectionExpression<TSource>
  33. {
  34. /// <summary>
  35. /// The expression cache
  36. /// </summary>
  37. private static readonly Dictionary<string, Expression> ExpressionCache = new Dictionary<string, Expression>();
  38. /// <summary>
  39. /// The source
  40. /// </summary>
  41. private readonly IQueryable<TSource> _source;
  42. /// <summary>
  43. /// Initializes a new instance of the <see cref="ProjectionExpression{TSource}"/> class.
  44. /// </summary>
  45. /// <param name="source">The source.</param>
  46. public ProjectionExpression(IQueryable<TSource> source)
  47. {
  48. _source = source;
  49. }
  50. /// <summary>
  51. /// To this instance.
  52. /// </summary>
  53. /// <typeparam name="TDest">The type of the dest.</typeparam>
  54. /// <returns></returns>
  55. public IQueryable<TDest> To<TDest>()
  56. {
  57. var queryExpression = GetCachedExpression<TDest>() ?? BuildExpression<TDest>();
  58. return _source.Select(queryExpression);
  59. }
  60. /// <summary>
  61. /// Gets the cached expression.
  62. /// </summary>
  63. /// <typeparam name="TDest">The type of the dest.</typeparam>
  64. /// <returns></returns>
  65. private static Expression<Func<TSource, TDest>> GetCachedExpression<TDest>()
  66. {
  67. var key = GetCacheKey<TDest>();
  68. return ExpressionCache.ContainsKey(key) ? ExpressionCache[key] as Expression<Func<TSource, TDest>> : null;
  69. }
  70. /// <summary>
  71. /// Builds the expression.
  72. /// </summary>
  73. /// <typeparam name="TDest">The type of the dest.</typeparam>
  74. /// <returns></returns>
  75. private static Expression<Func<TSource, TDest>> BuildExpression<TDest>()
  76. {
  77. var sourceProperties = typeof(TSource).GetProperties();
  78. var destinationProperties = typeof(TDest).GetProperties().Where(dest => dest.CanWrite);
  79. var parameterExpression = Expression.Parameter(typeof(TSource), "src");
  80. var bindings = destinationProperties
  81. .Select(destinationProperty => BuildBinding(parameterExpression, destinationProperty, sourceProperties))
  82. .Where(binding => binding != null);
  83. var expression = Expression.Lambda<Func<TSource, TDest>>(Expression.MemberInit(Expression.New(typeof(TDest)), bindings), parameterExpression);
  84. var key = GetCacheKey<TDest>();
  85. ExpressionCache.Add(key, expression);
  86. return expression;
  87. }
  88. /// <summary>
  89. /// Builds the binding.
  90. /// </summary>
  91. /// <param name="parameterExpression">The parameter expression.</param>
  92. /// <param name="destinationProperty">The destination property.</param>
  93. /// <param name="sourceProperties">The source properties.</param>
  94. /// <returns></returns>
  95. private static MemberAssignment BuildBinding(Expression parameterExpression, MemberInfo destinationProperty, IEnumerable<PropertyInfo> sourceProperties)
  96. {
  97. var sourceProperty = sourceProperties.FirstOrDefault(src => src.Name == destinationProperty.Name);
  98. if (sourceProperty != null) {
  99. return Expression.Bind(destinationProperty, Expression.Property(parameterExpression, sourceProperty));
  100. }
  101. var propertyNames = SplitCamelCase(destinationProperty.Name);
  102. if (propertyNames.Length == 2) {
  103. sourceProperty = sourceProperties.FirstOrDefault(src => src.Name == propertyNames[0]);
  104. if (sourceProperty != null) {
  105. var sourceChildProperty = sourceProperty.PropertyType.GetProperties().FirstOrDefault(src => src.Name == propertyNames[1]);
  106. if (sourceChildProperty != null) {
  107. return Expression.Bind(destinationProperty, Expression.Property(Expression.Property(parameterExpression, sourceProperty), sourceChildProperty));
  108. }
  109. }
  110. }
  111. return null;
  112. }
  113. /// <summary>
  114. /// Gets the cache key.
  115. /// </summary>
  116. /// <typeparam name="TDest">The type of the dest.</typeparam>
  117. /// <returns></returns>
  118. private static string GetCacheKey<TDest>()
  119. {
  120. return string.Concat(typeof(TSource).FullName, typeof(TDest).FullName);
  121. }
  122. /// <summary>
  123. /// Splits the camel case.
  124. /// </summary>
  125. /// <param name="input">The input.</param>
  126. /// <returns></returns>
  127. private static string[] SplitCamelCase(string input)
  128. {
  129. return Regex.Replace(input, "([A-Z])", " $1", RegexOptions.Compiled).Trim().Split(' ');
  130. }
  131. }
  132. }