PageRenderTime 48ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/mcs/class/referencesource/System.Data.Linq/SqlClient/Query/Translator.cs

http://github.com/mono/mono
C# | 521 lines | 446 code | 45 blank | 30 comment | 166 complexity | 76a3146022956883516cf83c8f4694e2 MD5 | raw file
Possible License(s): GPL-2.0, CC-BY-SA-3.0, LGPL-2.0, MPL-2.0-no-copyleft-exception, LGPL-2.1, Unlicense, Apache-2.0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq.Expressions;
  4. using System.Reflection;
  5. using System.Collections.ObjectModel;
  6. using System.Text;
  7. using System.Data.Linq;
  8. using System.Data.Linq.Mapping;
  9. using System.Data.Linq.Provider;
  10. using System.Linq;
  11. using System.Diagnostics.CodeAnalysis;
  12. namespace System.Data.Linq.SqlClient {
  13. internal class Translator {
  14. IDataServices services;
  15. SqlFactory sql;
  16. TypeSystemProvider typeProvider;
  17. internal Translator(IDataServices services, SqlFactory sqlFactory, TypeSystemProvider typeProvider) {
  18. this.services = services;
  19. this.sql = sqlFactory;
  20. this.typeProvider = typeProvider;
  21. }
  22. internal SqlSelect BuildDefaultQuery(MetaType rowType, bool allowDeferred, SqlLink link, Expression source) {
  23. System.Diagnostics.Debug.Assert(rowType != null && rowType.Table != null);
  24. if (rowType.HasInheritance && rowType.InheritanceRoot != rowType) {
  25. // RowType is expected to be an inheritance root.
  26. throw Error.ArgumentWrongValue("rowType");
  27. }
  28. SqlTable table = sql.Table(rowType.Table, rowType, source);
  29. SqlAlias tableAlias = new SqlAlias(table);
  30. SqlAliasRef tableAliasRef = new SqlAliasRef(tableAlias);
  31. SqlExpression projection = this.BuildProjection(tableAliasRef, table.RowType, allowDeferred, link, source);
  32. return new SqlSelect(projection, tableAlias, source);
  33. }
  34. internal SqlExpression BuildProjection(SqlExpression item, MetaType rowType, bool allowDeferred, SqlLink link, Expression source) {
  35. if (!rowType.HasInheritance) {
  36. return this.BuildProjectionInternal(item, rowType, (rowType.Table != null) ? rowType.PersistentDataMembers : rowType.DataMembers, allowDeferred, link, source);
  37. }
  38. else {
  39. // Build a type case that represents a switch between the various type.
  40. List<MetaType> mappedTypes = new List<MetaType>(rowType.InheritanceTypes);
  41. List<SqlTypeCaseWhen> whens = new List<SqlTypeCaseWhen>();
  42. SqlTypeCaseWhen @else = null;
  43. MetaType root = rowType.InheritanceRoot;
  44. MetaDataMember discriminator = root.Discriminator;
  45. Type dt = discriminator.Type;
  46. SqlMember dm = sql.Member(item, discriminator.Member);
  47. foreach (MetaType type in mappedTypes) {
  48. if (type.HasInheritanceCode) {
  49. SqlNew defaultProjection = this.BuildProjectionInternal(item, type, type.PersistentDataMembers, allowDeferred, link, source);
  50. if (type.IsInheritanceDefault) {
  51. @else = new SqlTypeCaseWhen(null, defaultProjection);
  52. }
  53. // Add an explicit case even for the default.
  54. // Redundant results will be optimized out later.
  55. object code = InheritanceRules.InheritanceCodeForClientCompare(type.InheritanceCode, dm.SqlType);
  56. SqlExpression match = sql.Value(dt, sql.Default(discriminator), code, true, source);
  57. whens.Add(new SqlTypeCaseWhen(match, defaultProjection));
  58. }
  59. }
  60. if (@else == null) {
  61. throw Error.EmptyCaseNotSupported();
  62. }
  63. whens.Add(@else); // Add the else at the end.
  64. return sql.TypeCase(root.Type, root, dm, whens.ToArray(), source);
  65. }
  66. }
  67. /// <summary>
  68. /// Check whether this member will be preloaded.
  69. /// </summary>
  70. private bool IsPreloaded(MemberInfo member) {
  71. if (this.services.Context.LoadOptions == null) {
  72. return false;
  73. }
  74. return this.services.Context.LoadOptions.IsPreloaded(member);
  75. }
  76. private SqlNew BuildProjectionInternal(SqlExpression item, MetaType rowType, IEnumerable<MetaDataMember> members, bool allowDeferred, SqlLink link, Expression source) {
  77. List<SqlMemberAssign> bindings = new List<SqlMemberAssign>();
  78. foreach (MetaDataMember mm in members) {
  79. if (allowDeferred && (mm.IsAssociation || mm.IsDeferred)) {
  80. // check if this member is the reverse association to the supplied link
  81. if (link != null && mm != link.Member && mm.IsAssociation
  82. && mm.MappedName == link.Member.MappedName
  83. && !mm.Association.IsMany
  84. && !IsPreloaded(link.Member.Member)) {
  85. // place a new link here with an expansion that is previous link's root expression.
  86. // this will allow joins caused by reverse association references to 'melt' away. :-)
  87. SqlLink mlink = this.BuildLink(item, mm, source);
  88. mlink.Expansion = link.Expression;
  89. bindings.Add(new SqlMemberAssign(mm.Member, mlink));
  90. }
  91. else {
  92. bindings.Add(new SqlMemberAssign(mm.Member, this.BuildLink(item, mm, source)));
  93. }
  94. }
  95. else if (!mm.IsAssociation) {
  96. bindings.Add(new SqlMemberAssign(mm.Member, sql.Member(item, mm)));
  97. }
  98. }
  99. ConstructorInfo cons = rowType.Type.GetConstructor(BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic, null, System.Type.EmptyTypes, null);
  100. if (cons == null) {
  101. throw Error.MappedTypeMustHaveDefaultConstructor(rowType.Type);
  102. }
  103. return sql.New(rowType, cons, null, null, bindings, source);
  104. }
  105. private SqlLink BuildLink(SqlExpression item, MetaDataMember member, Expression source) {
  106. if (member.IsAssociation) {
  107. SqlExpression[] exprs = new SqlExpression[member.Association.ThisKey.Count];
  108. for (int i = 0, n = exprs.Length; i < n; i++) {
  109. MetaDataMember mm = member.Association.ThisKey[i];
  110. exprs[i] = sql.Member(item, mm.Member);
  111. }
  112. MetaType otherType = member.Association.OtherType;
  113. return new SqlLink(new object(), otherType, member.Type, typeProvider.From(member.Type), item, member, exprs, null, source);
  114. }
  115. else {
  116. // if not association link is always based on primary key
  117. MetaType thisType = member.DeclaringType;
  118. System.Diagnostics.Debug.Assert(thisType.IsEntity);
  119. List<SqlExpression> exprs = new List<SqlExpression>();
  120. foreach (MetaDataMember mm in thisType.IdentityMembers) {
  121. exprs.Add(sql.Member(item, mm.Member));
  122. }
  123. SqlExpression expansion = sql.Member(item, member.Member);
  124. return new SqlLink(new object(), thisType, member.Type, typeProvider.From(member.Type), item, member, exprs, expansion, source);
  125. }
  126. }
  127. internal SqlNode TranslateLink(SqlLink link, bool asExpression) {
  128. return this.TranslateLink(link, link.KeyExpressions, asExpression);
  129. }
  130. /// <summary>
  131. /// Create an Expression representing the given association and key value expressions.
  132. /// </summary>
  133. internal static Expression TranslateAssociation(DataContext context, MetaAssociation association, Expression otherSource, Expression[] keyValues, Expression thisInstance) {
  134. if (association == null)
  135. throw Error.ArgumentNull("association");
  136. if (keyValues == null)
  137. throw Error.ArgumentNull("keyValues");
  138. if (context.LoadOptions!=null) {
  139. LambdaExpression subquery = context.LoadOptions.GetAssociationSubquery(association.ThisMember.Member);
  140. if (subquery!=null) {
  141. RelationComposer rc = new RelationComposer(subquery.Parameters[0], association, otherSource, thisInstance);
  142. return rc.Visit(subquery.Body);
  143. }
  144. }
  145. return WhereClauseFromSourceAndKeys(otherSource, association.OtherKey.ToArray(), keyValues);
  146. }
  147. internal static Expression WhereClauseFromSourceAndKeys(Expression source, MetaDataMember[] keyMembers, Expression [] keyValues) {
  148. Type elementType = TypeSystem.GetElementType(source.Type);
  149. ParameterExpression p = Expression.Parameter(elementType, "p");
  150. Expression whereExpression=null;
  151. for (int i = 0; i < keyMembers.Length; i++) {
  152. MetaDataMember metaMember = keyMembers[i];
  153. Expression parameterAsDeclaring = elementType == metaMember.Member.DeclaringType ?
  154. (Expression)p : (Expression)Expression.Convert(p, metaMember.Member.DeclaringType);
  155. Expression memberExpression = (metaMember.Member is FieldInfo)
  156. ? Expression.Field(parameterAsDeclaring, (FieldInfo)metaMember.Member)
  157. : Expression.Property(parameterAsDeclaring, (PropertyInfo)metaMember.Member);
  158. Expression keyValue = keyValues[i];
  159. if (keyValue.Type != memberExpression.Type)
  160. keyValue = Expression.Convert(keyValue, memberExpression.Type);
  161. Expression memberEqualityExpression = Expression.Equal(memberExpression, keyValue);
  162. whereExpression = (whereExpression != null)
  163. ? Expression.And(whereExpression, memberEqualityExpression)
  164. : memberEqualityExpression;
  165. }
  166. Expression sequenceExpression = Expression.Call(typeof(Enumerable), "Where", new Type[] {p.Type}, source, Expression.Lambda(whereExpression, p));
  167. return sequenceExpression;
  168. }
  169. /// <summary>
  170. /// Composes a subquery into a linked association.
  171. /// </summary>
  172. private class RelationComposer : ExpressionVisitor {
  173. ParameterExpression parameter;
  174. MetaAssociation association;
  175. Expression otherSouce;
  176. Expression parameterReplacement;
  177. internal RelationComposer(ParameterExpression parameter, MetaAssociation association, Expression otherSouce, Expression parameterReplacement) {
  178. if (parameter==null)
  179. throw Error.ArgumentNull("parameter");
  180. if (association == null)
  181. throw Error.ArgumentNull("association");
  182. if (otherSouce == null)
  183. throw Error.ArgumentNull("otherSouce");
  184. if (parameterReplacement==null)
  185. throw Error.ArgumentNull("parameterReplacement");
  186. this.parameter = parameter;
  187. this.association = association;
  188. this.otherSouce = otherSouce;
  189. this.parameterReplacement = parameterReplacement;
  190. }
  191. internal override Expression VisitParameter(ParameterExpression p) {
  192. if (p == parameter) {
  193. return this.parameterReplacement;
  194. }
  195. return base.VisitParameter(p);
  196. }
  197. private static Expression[] GetKeyValues(Expression expr, ReadOnlyCollection<MetaDataMember> keys) {
  198. List<Expression> values = new List<Expression>();
  199. foreach(MetaDataMember key in keys){
  200. values.Add(Expression.PropertyOrField(expr, key.Name));
  201. }
  202. return values.ToArray();
  203. }
  204. internal override Expression VisitMemberAccess(MemberExpression m) {
  205. if (MetaPosition.AreSameMember(m.Member, this.association.ThisMember.Member)) {
  206. Expression[] keyValues = GetKeyValues(this.Visit(m.Expression), this.association.ThisKey);
  207. return WhereClauseFromSourceAndKeys(this.otherSouce, this.association.OtherKey.ToArray(), keyValues);
  208. }
  209. Expression exp = this.Visit(m.Expression);
  210. if (exp != m.Expression) {
  211. if (exp.Type != m.Expression.Type && m.Member.Name == "Count" && TypeSystem.IsSequenceType(exp.Type)) {
  212. return Expression.Call(typeof(Enumerable), "Count", new Type[] {TypeSystem.GetElementType(exp.Type)}, exp);
  213. }
  214. return Expression.MakeMemberAccess(exp, m.Member);
  215. }
  216. return m;
  217. }
  218. }
  219. internal SqlNode TranslateLink(SqlLink link, List<SqlExpression> keyExpressions, bool asExpression) {
  220. MetaDataMember mm = link.Member;
  221. if (mm.IsAssociation) {
  222. // Create the row source.
  223. MetaType otherType = mm.Association.OtherType;
  224. Type tableType = otherType.InheritanceRoot.Type;
  225. ITable table = this.services.Context.GetTable(tableType);
  226. Expression source = new LinkedTableExpression(link, table, typeof(IQueryable<>).MakeGenericType(otherType.Type));
  227. // Build key expression nodes.
  228. Expression[] keyExprs = new Expression[keyExpressions.Count];
  229. for (int i = 0; i < keyExpressions.Count; ++i) {
  230. MetaDataMember metaMember = mm.Association.OtherKey[i];
  231. Type memberType = TypeSystem.GetMemberType(metaMember.Member);
  232. keyExprs[i] = InternalExpression.Known(keyExpressions[i], memberType);
  233. }
  234. Expression lex = link.Expression != null
  235. ? (Expression)InternalExpression.Known(link.Expression)
  236. : (Expression)Expression.Constant(null, link.Member.Member.DeclaringType);
  237. Expression expr = TranslateAssociation(this.services.Context, mm.Association, source, keyExprs, lex);
  238. // Convert
  239. QueryConverter qc = new QueryConverter(this.services, this.typeProvider, this, this.sql);
  240. SqlSelect sel = (SqlSelect)qc.ConvertInner(expr, link.SourceExpression);
  241. // Turn it into an expression is necessary
  242. SqlNode result = sel;
  243. if (asExpression) {
  244. if (mm.Association.IsMany) {
  245. result = new SqlSubSelect(SqlNodeType.Multiset, link.ClrType, link.SqlType, sel);
  246. }
  247. else {
  248. result = new SqlSubSelect(SqlNodeType.Element, link.ClrType, link.SqlType, sel);
  249. }
  250. }
  251. return result;
  252. }
  253. else {
  254. System.Diagnostics.Debug.Assert(link.Expansion != null);
  255. System.Diagnostics.Debug.Assert(link.KeyExpressions == keyExpressions);
  256. // deferred expression already defined...
  257. return link.Expansion;
  258. }
  259. }
  260. [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification="These issues are related to our use of if-then and case statements for node types, which adds to the complexity count however when reviewed they are easy to navigate and understand.")]
  261. internal SqlExpression TranslateEquals(SqlBinary expr) {
  262. System.Diagnostics.Debug.Assert(
  263. expr.NodeType == SqlNodeType.EQ || expr.NodeType == SqlNodeType.NE ||
  264. expr.NodeType == SqlNodeType.EQ2V || expr.NodeType == SqlNodeType.NE2V);
  265. SqlExpression eLeft = expr.Left;
  266. SqlExpression eRight = expr.Right;
  267. if (eRight.NodeType == SqlNodeType.Element) {
  268. SqlSubSelect sub = (SqlSubSelect)eRight;
  269. SqlAlias alias = new SqlAlias(sub.Select);
  270. SqlAliasRef aref = new SqlAliasRef(alias);
  271. SqlSelect select = new SqlSelect(aref, alias, expr.SourceExpression);
  272. select.Where = sql.Binary(expr.NodeType, sql.DoNotVisitExpression(eLeft), aref);
  273. return sql.SubSelect(SqlNodeType.Exists, select);
  274. }
  275. else if (eLeft.NodeType == SqlNodeType.Element) {
  276. SqlSubSelect sub = (SqlSubSelect)eLeft;
  277. SqlAlias alias = new SqlAlias(sub.Select);
  278. SqlAliasRef aref = new SqlAliasRef(alias);
  279. SqlSelect select = new SqlSelect(aref, alias, expr.SourceExpression);
  280. select.Where = sql.Binary(expr.NodeType, sql.DoNotVisitExpression(eRight), aref);
  281. return sql.SubSelect(SqlNodeType.Exists, select);
  282. }
  283. MetaType mtLeft = TypeSource.GetSourceMetaType(eLeft, this.services.Model);
  284. MetaType mtRight = TypeSource.GetSourceMetaType(eRight, this.services.Model);
  285. if (eLeft.NodeType == SqlNodeType.TypeCase) {
  286. eLeft = BestIdentityNode((SqlTypeCase)eLeft);
  287. }
  288. if (eRight.NodeType == SqlNodeType.TypeCase) {
  289. eRight = BestIdentityNode((SqlTypeCase)eRight);
  290. }
  291. if (mtLeft.IsEntity && mtRight.IsEntity && mtLeft.Table != mtRight.Table) {
  292. throw Error.CannotCompareItemsAssociatedWithDifferentTable();
  293. }
  294. // do simple or no translation for non-structural types
  295. if (!mtLeft.IsEntity && !mtRight.IsEntity &&
  296. (eLeft.NodeType != SqlNodeType.New || eLeft.SqlType.CanBeColumn) &&
  297. (eRight.NodeType != SqlNodeType.New || eRight.SqlType.CanBeColumn)) {
  298. if (expr.NodeType == SqlNodeType.EQ2V || expr.NodeType == SqlNodeType.NE2V) {
  299. return this.TranslateEqualsOp(expr.NodeType, sql.DoNotVisitExpression(expr.Left), sql.DoNotVisitExpression(expr.Right), false);
  300. }
  301. return expr;
  302. }
  303. // If the two types are not comparable, we return the predicate "1=0".
  304. if ((mtLeft != mtRight) && (mtLeft.InheritanceRoot != mtRight.InheritanceRoot)) {
  305. return sql.Binary(SqlNodeType.EQ, sql.ValueFromObject(0,expr.SourceExpression), sql.ValueFromObject(1,expr.SourceExpression));
  306. }
  307. List<SqlExpression> exprs1;
  308. List<SqlExpression> exprs2;
  309. SqlLink link1 = eLeft as SqlLink;
  310. if (link1 != null && link1.Member.IsAssociation && link1.Member.Association.IsForeignKey) {
  311. exprs1 = link1.KeyExpressions;
  312. }
  313. else {
  314. exprs1 = this.GetIdentityExpressions(mtLeft, sql.DoNotVisitExpression(eLeft));
  315. }
  316. SqlLink link2 = eRight as SqlLink;
  317. if (link2 != null && link2.Member.IsAssociation && link2.Member.Association.IsForeignKey) {
  318. exprs2 = link2.KeyExpressions;
  319. }
  320. else {
  321. exprs2 = this.GetIdentityExpressions(mtRight, sql.DoNotVisitExpression(eRight));
  322. }
  323. System.Diagnostics.Debug.Assert(exprs1.Count > 0);
  324. System.Diagnostics.Debug.Assert(exprs2.Count > 0);
  325. System.Diagnostics.Debug.Assert(exprs1.Count == exprs2.Count);
  326. SqlExpression exp = null;
  327. SqlNodeType eqKind = (expr.NodeType == SqlNodeType.EQ2V || expr.NodeType == SqlNodeType.NE2V) ? SqlNodeType.EQ2V : SqlNodeType.EQ;
  328. for (int i = 0, n = exprs1.Count; i < n; i++) {
  329. SqlExpression eq = this.TranslateEqualsOp(eqKind, exprs1[i], exprs2[i], !mtLeft.IsEntity);
  330. if (exp == null) {
  331. exp = eq;
  332. }
  333. else {
  334. exp = sql.Binary(SqlNodeType.And, exp, eq);
  335. }
  336. }
  337. if (expr.NodeType == SqlNodeType.NE || expr.NodeType == SqlNodeType.NE2V) {
  338. exp = sql.Unary(SqlNodeType.Not, exp, exp.SourceExpression);
  339. }
  340. return exp;
  341. }
  342. private SqlExpression TranslateEqualsOp(SqlNodeType op, SqlExpression left, SqlExpression right, bool allowExpand) {
  343. switch (op) {
  344. case SqlNodeType.EQ:
  345. case SqlNodeType.NE:
  346. return sql.Binary(op, left, right);
  347. case SqlNodeType.EQ2V:
  348. if (SqlExpressionNullability.CanBeNull(left) != false &&
  349. SqlExpressionNullability.CanBeNull(right) != false) {
  350. SqlNodeType eqOp = allowExpand ? SqlNodeType.EQ2V : SqlNodeType.EQ;
  351. return
  352. sql.Binary(SqlNodeType.Or,
  353. sql.Binary(SqlNodeType.And,
  354. sql.Unary(SqlNodeType.IsNull, (SqlExpression)SqlDuplicator.Copy(left)),
  355. sql.Unary(SqlNodeType.IsNull, (SqlExpression)SqlDuplicator.Copy(right))
  356. ),
  357. sql.Binary(SqlNodeType.And,
  358. sql.Binary(SqlNodeType.And,
  359. sql.Unary(SqlNodeType.IsNotNull, (SqlExpression)SqlDuplicator.Copy(left)),
  360. sql.Unary(SqlNodeType.IsNotNull, (SqlExpression)SqlDuplicator.Copy(right))
  361. ),
  362. sql.Binary(eqOp, left, right)
  363. )
  364. );
  365. }
  366. else {
  367. SqlNodeType eqOp = allowExpand ? SqlNodeType.EQ2V : SqlNodeType.EQ;
  368. return sql.Binary(eqOp, left, right);
  369. }
  370. case SqlNodeType.NE2V:
  371. if (SqlExpressionNullability.CanBeNull(left) != false &&
  372. SqlExpressionNullability.CanBeNull(right) != false) {
  373. SqlNodeType eqOp = allowExpand ? SqlNodeType.EQ2V : SqlNodeType.EQ;
  374. return
  375. sql.Unary(SqlNodeType.Not,
  376. sql.Binary(SqlNodeType.Or,
  377. sql.Binary(SqlNodeType.And,
  378. sql.Unary(SqlNodeType.IsNull, (SqlExpression)SqlDuplicator.Copy(left)),
  379. sql.Unary(SqlNodeType.IsNull, (SqlExpression)SqlDuplicator.Copy(right))
  380. ),
  381. sql.Binary(SqlNodeType.And,
  382. sql.Binary(SqlNodeType.And,
  383. sql.Unary(SqlNodeType.IsNotNull, (SqlExpression)SqlDuplicator.Copy(left)),
  384. sql.Unary(SqlNodeType.IsNotNull, (SqlExpression)SqlDuplicator.Copy(right))
  385. ),
  386. sql.Binary(eqOp, left, right)
  387. )
  388. )
  389. );
  390. }
  391. else {
  392. SqlNodeType neOp = allowExpand ? SqlNodeType.NE2V : SqlNodeType.NE;
  393. return sql.Binary(neOp, left, right);
  394. }
  395. default:
  396. throw Error.UnexpectedNode(op);
  397. }
  398. }
  399. internal SqlExpression TranslateLinkEquals(SqlBinary bo) {
  400. SqlLink link1 = bo.Left as SqlLink;
  401. SqlLink link2 = bo.Right as SqlLink;
  402. if ((link1 != null && link1.Member.IsAssociation && link1.Member.Association.IsForeignKey) ||
  403. (link2 != null && link2.Member.IsAssociation && link2.Member.Association.IsForeignKey)) {
  404. return this.TranslateEquals(bo);
  405. }
  406. return bo;
  407. }
  408. internal SqlExpression TranslateLinkIsNull(SqlUnary expr) {
  409. System.Diagnostics.Debug.Assert(expr.NodeType == SqlNodeType.IsNull || expr.NodeType == SqlNodeType.IsNotNull);
  410. SqlLink link = expr.Operand as SqlLink;
  411. if (!(link != null && link.Member.IsAssociation && link.Member.Association.IsForeignKey)) {
  412. return expr;
  413. }
  414. List<SqlExpression> exprs = link.KeyExpressions;
  415. System.Diagnostics.Debug.Assert(exprs.Count > 0);
  416. SqlExpression exp = null;
  417. SqlNodeType combo = (expr.NodeType == SqlNodeType.IsNull) ? SqlNodeType.Or : SqlNodeType.And;
  418. for (int i = 0, n = exprs.Count; i < n; i++) {
  419. SqlExpression compare = sql.Unary(expr.NodeType, sql.DoNotVisitExpression(exprs[i]), expr.SourceExpression);
  420. if (exp == null) {
  421. exp = compare;
  422. }
  423. else {
  424. exp = sql.Binary(combo, exp, compare);
  425. }
  426. }
  427. return exp;
  428. }
  429. /// <summary>
  430. /// Find the alternative in type case that will best identify the object.
  431. /// If there is a SqlNew it is expected to have all the identity fields.
  432. /// If there is no SqlNew then we must be dealing with all literal NULL alternatives. In this case,
  433. /// just return the first one.
  434. /// </summary>
  435. private static SqlExpression BestIdentityNode(SqlTypeCase tc) {
  436. foreach (SqlTypeCaseWhen when in tc.Whens) {
  437. if (when.TypeBinding.NodeType == SqlNodeType.New) {
  438. return when.TypeBinding;
  439. }
  440. }
  441. return tc.Whens[0].TypeBinding; // There were no SqlNews, take the first alternative
  442. }
  443. private static bool IsPublic(MemberInfo mi) {
  444. FieldInfo fi = mi as FieldInfo;
  445. if (fi != null) {
  446. return fi.IsPublic;
  447. }
  448. PropertyInfo pi = mi as PropertyInfo;
  449. if (pi != null) {
  450. if (pi.CanRead) {
  451. var gm = pi.GetGetMethod();
  452. if (gm != null) {
  453. return gm.IsPublic;
  454. }
  455. }
  456. }
  457. return false;
  458. }
  459. [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification="Unknown reason.")]
  460. private IEnumerable<MetaDataMember> GetIdentityMembers(MetaType type) {
  461. if (type.IsEntity) {
  462. return type.IdentityMembers;
  463. }
  464. return type.DataMembers.Where(m => IsPublic(m.Member));
  465. }
  466. private List<SqlExpression> GetIdentityExpressions(MetaType type, SqlExpression expr) {
  467. List<MetaDataMember> members = GetIdentityMembers(type).ToList();
  468. System.Diagnostics.Debug.Assert(members.Count > 0);
  469. List<SqlExpression> exprs = new List<SqlExpression>(members.Count);
  470. foreach (MetaDataMember mm in members) {
  471. exprs.Add(sql.Member((SqlExpression)SqlDuplicator.Copy(expr), mm));
  472. }
  473. return exprs;
  474. }
  475. }
  476. }