DataShape.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Reflection;
  5. using System.Linq;
  6. using System.Linq.Expressions;
  7. using System.Collections;
  8. using System.Data.Linq.SqlClient;
  9. using System.Diagnostics.CodeAnalysis;
  10. namespace System.Data.Linq {
  11. sealed public class DataLoadOptions {
  12. bool frozen;
  13. Dictionary<MetaPosition, MemberInfo> includes = new Dictionary<MetaPosition, MemberInfo>();
  14. Dictionary<MetaPosition, LambdaExpression> subqueries = new Dictionary<MetaPosition, LambdaExpression>();
  15. /// <summary>
  16. /// Describe a property that is automatically loaded when the containing instance is loaded
  17. /// </summary>
  18. [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "[....]: Generic types are an important part of Linq APIs and they could not exist without nested generic support.")]
  19. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "[....]: Need to provide static typing.")]
  20. public void LoadWith<T>(Expression<Func<T, object>> expression) {
  21. if (expression == null) {
  22. throw Error.ArgumentNull("expression");
  23. }
  24. MemberInfo mi = GetLoadWithMemberInfo(expression);
  25. this.Preload(mi);
  26. }
  27. /// <summary>
  28. /// Describe a property that is automatically loaded when the containing instance is loaded
  29. /// </summary>
  30. public void LoadWith(LambdaExpression expression) {
  31. if (expression == null) {
  32. throw Error.ArgumentNull("expression");
  33. }
  34. MemberInfo mi = GetLoadWithMemberInfo(expression);
  35. this.Preload(mi);
  36. }
  37. /// <summary>
  38. /// Place a subquery on the given association.
  39. /// </summary>
  40. [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "[....]: Generic types are an important part of Linq APIs and they could not exist without nested generic support.")]
  41. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "[....]: Need to provide static typing.")]
  42. public void AssociateWith<T>(Expression<Func<T, object>> expression) {
  43. if (expression == null) {
  44. throw Error.ArgumentNull("expression");
  45. }
  46. this.AssociateWithInternal(expression);
  47. }
  48. /// <summary>
  49. /// Place a subquery on the given association.
  50. /// </summary>
  51. public void AssociateWith(LambdaExpression expression) {
  52. if (expression == null) {
  53. throw Error.ArgumentNull("expression");
  54. }
  55. this.AssociateWithInternal(expression);
  56. }
  57. private void AssociateWithInternal(LambdaExpression expression) {
  58. // Strip the cast-to-object.
  59. Expression op = expression.Body;
  60. while (op.NodeType == ExpressionType.Convert || op.NodeType == ExpressionType.ConvertChecked) {
  61. op = ((UnaryExpression)op).Operand;
  62. }
  63. LambdaExpression lambda = Expression.Lambda(op, expression.Parameters.ToArray());
  64. MemberInfo mi = Searcher.MemberInfoOf(lambda);
  65. this.Subquery(mi, lambda);
  66. }
  67. /// <summary>
  68. /// Determines if the member is automatically loaded with its containing instances.
  69. /// </summary>
  70. /// <param name="member">The member this is automatically loaded.</param>
  71. /// <returns>True if the member is automatically loaded.</returns>
  72. internal bool IsPreloaded(MemberInfo member) {
  73. if (member == null) {
  74. throw Error.ArgumentNull("member");
  75. }
  76. return includes.ContainsKey(new MetaPosition(member));
  77. }
  78. /// <summary>
  79. /// Two shapes are equivalent if any of the following are true:
  80. /// (1) They are the same object instance
  81. /// (2) They are both null or empty
  82. /// (3) They contain the same preloaded members
  83. /// </summary>
  84. internal static bool ShapesAreEquivalent(DataLoadOptions ds1, DataLoadOptions ds2) {
  85. bool shapesAreSameOrEmpty = (ds1 == ds2) || ((ds1 == null || ds1.IsEmpty) && (ds2 == null || ds2.IsEmpty));
  86. if (!shapesAreSameOrEmpty) {
  87. if (ds1 == null || ds2 == null || ds1.includes.Count != ds2.includes.Count) {
  88. return false;
  89. }
  90. foreach (MetaPosition metaPosition in ds2.includes.Keys) {
  91. if (!ds1.includes.ContainsKey(metaPosition)) {
  92. return false;
  93. }
  94. }
  95. }
  96. return true;
  97. }
  98. /// <summary>
  99. /// Gets the subquery expression associated with the member.
  100. /// </summary>
  101. /// <param name="member">The member with the subquery.</param>
  102. /// <returns></returns>
  103. internal LambdaExpression GetAssociationSubquery(MemberInfo member) {
  104. if (member == null) {
  105. throw Error.ArgumentNull("member");
  106. }
  107. LambdaExpression expression = null;
  108. subqueries.TryGetValue(new MetaPosition(member), out expression);
  109. return expression;
  110. }
  111. /// <summary>
  112. /// Freeze the shape. Any further attempts to modify the shape will result in
  113. /// an exception.
  114. /// </summary>
  115. internal void Freeze() {
  116. this.frozen = true;
  117. }
  118. /// <summary>
  119. /// Describe a property that is automatically loaded when the containing instance is loaded
  120. /// </summary>
  121. internal void Preload(MemberInfo association) {
  122. if (association == null) {
  123. throw Error.ArgumentNull("association");
  124. }
  125. if (this.frozen) {
  126. throw Error.IncludeNotAllowedAfterFreeze();
  127. }
  128. this.includes.Add(new MetaPosition(association), association);
  129. ValidateTypeGraphAcyclic();
  130. }
  131. /// <summary>
  132. /// Place a subquery on the given association.
  133. /// </summary>
  134. private void Subquery(MemberInfo association, LambdaExpression subquery) {
  135. if (this.frozen) {
  136. throw Error.SubqueryNotAllowedAfterFreeze();
  137. }
  138. subquery = (LambdaExpression)System.Data.Linq.SqlClient.Funcletizer.Funcletize(subquery); // Layering violation.
  139. ValidateSubqueryMember(association);
  140. ValidateSubqueryExpression(subquery);
  141. this.subqueries[new MetaPosition(association)] = subquery;
  142. }
  143. /// <summary>
  144. /// If the lambda specified is of the form p.A, where p is the parameter
  145. /// and A is a member on p, the MemberInfo for A is returned. If
  146. /// the expression is not of this form, an exception is thrown.
  147. /// </summary>
  148. private static MemberInfo GetLoadWithMemberInfo(LambdaExpression lambda)
  149. {
  150. // When the specified member is a value type, there will be a conversion
  151. // to object that we need to strip
  152. Expression body = lambda.Body;
  153. if (body != null && (body.NodeType == ExpressionType.Convert || body.NodeType == ExpressionType.ConvertChecked))
  154. {
  155. body = ((UnaryExpression)body).Operand;
  156. }
  157. MemberExpression mex = body as MemberExpression;
  158. if (mex != null && mex.Expression.NodeType == ExpressionType.Parameter)
  159. {
  160. return mex.Member;
  161. }
  162. else
  163. {
  164. throw Error.InvalidLoadOptionsLoadMemberSpecification();
  165. }
  166. }
  167. private static class Searcher {
  168. static internal MemberInfo MemberInfoOf(LambdaExpression lambda) {
  169. Visitor v = new Visitor();
  170. v.VisitLambda(lambda);
  171. return v.MemberInfo;
  172. }
  173. private class Visitor : System.Data.Linq.SqlClient.ExpressionVisitor {
  174. internal MemberInfo MemberInfo;
  175. internal override Expression VisitMemberAccess(MemberExpression m) {
  176. this.MemberInfo = m.Member;
  177. return base.VisitMemberAccess(m);
  178. }
  179. internal override Expression VisitMethodCall(MethodCallExpression m) {
  180. this.Visit(m.Object);
  181. foreach (Expression arg in m.Arguments) {
  182. this.Visit(arg);
  183. break; // Only follow the extension method 'this'
  184. }
  185. return m;
  186. }
  187. }
  188. }
  189. private void ValidateTypeGraphAcyclic() {
  190. IEnumerable<MemberInfo> edges = this.includes.Values;
  191. int removed = 0;
  192. for (int loop = 0; loop < this.includes.Count; ++loop) {
  193. // Build a list of all edge targets.
  194. HashSet<Type> edgeTargets = new HashSet<Type>();
  195. foreach (MemberInfo edge in edges) {
  196. edgeTargets.Add(GetIncludeTarget(edge));
  197. }
  198. // Remove all edges with sources matching no target.
  199. List<MemberInfo> newEdges = new List<MemberInfo>();
  200. bool someRemoved = false;
  201. foreach (MemberInfo edge in edges) {
  202. if (edgeTargets.Where(et=>et.IsAssignableFrom(edge.DeclaringType) || edge.DeclaringType.IsAssignableFrom(et)).Any()) {
  203. newEdges.Add(edge);
  204. }
  205. else {
  206. ++removed;
  207. someRemoved = true;
  208. if (removed == this.includes.Count)
  209. return;
  210. }
  211. }
  212. if (!someRemoved) {
  213. throw Error.IncludeCycleNotAllowed(); // No edges removed, there must be a loop.
  214. }
  215. edges = newEdges;
  216. }
  217. throw new InvalidOperationException("Bug in ValidateTypeGraphAcyclic"); // Getting here means a bug.
  218. }
  219. private static Type GetIncludeTarget(MemberInfo mi) {
  220. Type mt = System.Data.Linq.SqlClient.TypeSystem.GetMemberType(mi);
  221. if (mt.IsGenericType) {
  222. return mt.GetGenericArguments()[0];
  223. }
  224. return mt;
  225. }
  226. private static void ValidateSubqueryMember(MemberInfo mi) {
  227. Type memberType = System.Data.Linq.SqlClient.TypeSystem.GetMemberType(mi);
  228. if (memberType == null) {
  229. throw Error.SubqueryNotSupportedOn(mi);
  230. }
  231. if (!typeof(IEnumerable).IsAssignableFrom(memberType)) {
  232. throw Error.SubqueryNotSupportedOnType(mi.Name, mi.DeclaringType);
  233. }
  234. }
  235. private static void ValidateSubqueryExpression(LambdaExpression subquery) {
  236. if (!typeof(IEnumerable).IsAssignableFrom(subquery.Body.Type)) {
  237. throw Error.SubqueryMustBeSequence();
  238. }
  239. new SubqueryValidator().VisitLambda(subquery);
  240. }
  241. /// <summary>
  242. /// Ensure that the subquery follows the rules for subqueries.
  243. /// </summary>
  244. private class SubqueryValidator : System.Data.Linq.SqlClient.ExpressionVisitor {
  245. bool isTopLevel = true;
  246. internal override Expression VisitMethodCall(MethodCallExpression m) {
  247. bool was = isTopLevel;
  248. try {
  249. if (isTopLevel && !SubqueryRules.IsSupportedTopLevelMethod(m.Method))
  250. throw Error.SubqueryDoesNotSupportOperator(m.Method.Name);
  251. isTopLevel = false;
  252. return base.VisitMethodCall(m);
  253. }
  254. finally {
  255. isTopLevel = was;
  256. }
  257. }
  258. }
  259. /// <summary>
  260. /// Whether there have been LoadOptions specified.
  261. /// </summary>
  262. internal bool IsEmpty {
  263. get { return this.includes.Count == 0 && this.subqueries.Count == 0; }
  264. }
  265. }
  266. }