Updates referencesource to .NET 4.7
[mono.git] / mcs / class / referencesource / System.Data.Entity / System / Data / Common / EntityUtil.cs
1 //------------------------------------------------------------------------------
2 // <copyright file="EntityUtil.cs" company="Microsoft">
3 //     Copyright (c) Microsoft Corporation.  All rights reserved.
4 // </copyright>
5 // <owner current="true" primary="true">Microsoft</owner>
6 //------------------------------------------------------------------------------
7
8 namespace System.Data {
9
10     using System;
11     using System.Collections;
12     using System.Collections.Generic;
13     using System.Data.Common;
14     using System.Data.Entity;
15     using System.Data.Mapping;
16     using System.Data.Metadata.Edm;
17     using System.Data.Objects;
18     using System.Data.Objects.Internal;
19     using System.Data.SqlTypes;
20     using System.Diagnostics;
21     using System.Diagnostics.CodeAnalysis;
22     using System.Globalization;
23     using System.IO;
24     using System.Linq;
25     using System.Reflection;
26     using System.Runtime.Versioning;
27     using System.Security.Permissions;
28     using System.Text;
29
30     internal static class EntityUtil {
31
32         internal const int AssemblyQualifiedNameIndex = 3;
33         internal const int InvariantNameIndex = 2;
34
35         internal const string Parameter = "Parameter";
36
37         internal const CompareOptions StringCompareOptions = CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase;
38
39         internal static bool? ThreeValuedNot(bool? operand) {
40             // three-valued logic 'not' (T = true, F = false, U = unknown)
41             //      !T = F
42             //      !F = T
43             //      !U = U
44             return operand.HasValue ? !operand.Value : (bool?)null;
45         }
46         internal static bool? ThreeValuedAnd(bool? left, bool? right) {
47             // three-valued logic 'and' (T = true, F = false, U = unknown)
48             //
49             //      T & T = T
50             //      T & F = F
51             //      F & F = F
52             //      F & T = F
53             //      F & U = F
54             //      U & F = F
55             //      T & U = U
56             //      U & T = U
57             //      U & U = U
58             bool? result;
59             if (left.HasValue && right.HasValue) {
60                 result = left.Value && right.Value;
61             }
62             else if (!left.HasValue && !right.HasValue) {
63                 result = null; // unknown
64             }
65             else if (left.HasValue) {
66                 result = left.Value ?
67                     (bool?)null :// unknown
68                     false;
69             }
70             else {
71                 result = right.Value ?
72                     (bool?)null :
73                     false;
74             }
75             return result;
76         }
77
78         internal static bool? ThreeValuedOr(bool? left, bool? right) {
79             // three-valued logic 'or' (T = true, F = false, U = unknown)
80             //
81             //      T | T = T
82             //      T | F = T
83             //      F | F = F
84             //      F | T = T
85             //      F | U = U
86             //      U | F = U
87             //      T | U = T
88             //      U | T = T
89             //      U | U = U
90             bool? result;
91             if (left.HasValue && right.HasValue) {
92                 result = left.Value || right.Value;
93             }
94             else if (!left.HasValue && !right.HasValue) {
95                 result = null; // unknown
96             }
97             else if (left.HasValue) {
98                 result = left.Value ?
99                     true :
100                     (bool?)null; // unknown
101             }
102             else {
103                 result = right.Value ?
104                     true :
105                     (bool?)null; // unknown
106             }
107             return result;
108         }
109
110         /// <summary>
111         /// Zips two enumerables together (e.g., given {1, 3, 5} and {2, 4, 6} returns {{1, 2}, {3, 4}, {5, 6}})
112         /// </summary>
113         internal static IEnumerable<KeyValuePair<T1, T2>> Zip<T1, T2>(this IEnumerable<T1> first, IEnumerable<T2> second)
114         {
115             if (null == first || null == second) { yield break; }
116             using (IEnumerator<T1> firstEnumerator = first.GetEnumerator())
117             using (IEnumerator<T2> secondEnumerator = second.GetEnumerator())
118             {
119                 while (firstEnumerator.MoveNext() && secondEnumerator.MoveNext())
120                 {
121                     yield return new KeyValuePair<T1, T2>(firstEnumerator.Current, secondEnumerator.Current);
122                 }
123             }
124         }
125
126         /// <summary>
127         /// Returns true if the type implements ICollection<>
128         /// </summary>
129         internal static bool IsAnICollection(Type type)
130         {
131             return typeof(ICollection<>).IsAssignableFrom(type.GetGenericTypeDefinition()) ||
132                     type.GetInterface(typeof(ICollection<>).FullName) != null;
133
134         }
135
136         /// <summary>
137         /// Given a type that represents a collection, determine if the type implements ICollection&lt&gt, and if
138         /// so return the element type of the collection.  Currently, if the collection implements ICollection&lt&gt
139         /// multiple times with different types, then we will return false since this is not supported.
140         /// </summary>
141         /// <param name="collectionType">the collection type to examine</param>
142         /// <param name="elementType">the type of element</param>
143         /// <returns>true if the collection implement ICollection&lt&gt; false otherwise</returns>
144         internal static bool TryGetICollectionElementType(Type collectionType, out Type elementType)
145         {
146             elementType = null;
147             // We have to check if the type actually is the interface, or if it implements the interface:
148             try
149             {
150                 Type collectionInterface =
151                      (collectionType.IsGenericType && typeof(ICollection<>).IsAssignableFrom(collectionType.GetGenericTypeDefinition())) ?
152                      collectionType :
153                      collectionType.GetInterface(typeof(ICollection<>).FullName);
154
155                 // We need to make sure the type is fully specified otherwise we won't be able to add element to it.
156                 if (collectionInterface != null && !collectionInterface.ContainsGenericParameters)
157                 {
158                     elementType = collectionInterface.GetGenericArguments()[0];
159                     return true;
160                 }
161
162             }
163             catch (AmbiguousMatchException)
164             {
165                 // Thrown if collection type implements ICollection<> more than once
166             }
167             return false;
168         }
169
170         /// <summary>
171         /// Helper method to determine the element type of the collection contained by the given property.
172         /// If an unambiguous element type cannot be found, then an InvalidOperationException is thrown.
173         /// </summary>
174         internal static Type GetCollectionElementType(Type propertyType)
175         {
176             Type elementType;
177             if (!EntityUtil.TryGetICollectionElementType(propertyType, out elementType))
178             {
179                 throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.PocoEntityWrapper_UnexpectedTypeForNavigationProperty(
180                                                   propertyType.FullName,
181                                                   typeof(ICollection<>)));
182             }
183             return elementType;
184         }
185
186         /// <summary>
187         /// This is used when we need to determine a concrete collection type given some type that may be
188         /// abstract or an interface.
189         /// </summary>
190         /// <remarks>
191         /// The rules are:
192         /// If the collection is defined as a concrete type with a publicly accessible parameterless constructor, then create an instance of that type
193         /// Else, if HashSet<T> can be assigned to the type, then use HashSet<T>
194         /// Else, if List<T> can be assigned to the type, then use List<T>
195         /// Else, throw a nice exception.
196         /// </remarks>
197         /// <param name="requestedType">The type of collection that was requested</param>
198         /// <returns>The type to instantiate, or null if we cannot find a supported type to instantiate</returns>
199         internal static Type DetermineCollectionType(Type requestedType)
200         {
201             const BindingFlags constructorBinding = BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance;
202
203             var elementType = EntityUtil.GetCollectionElementType(requestedType);
204
205             if (requestedType.IsArray)
206             {
207                 throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectQuery_UnableToMaterializeArray(
208                                                   requestedType, typeof(List<>).MakeGenericType(elementType)));
209             }
210
211             if (!requestedType.IsAbstract &&
212                 requestedType.GetConstructor(constructorBinding, null, System.Type.EmptyTypes, null) != null)
213             {
214                 return requestedType;
215             }
216
217             var hashSetOfT = typeof(HashSet<>).MakeGenericType(elementType);
218             if (requestedType.IsAssignableFrom(hashSetOfT))
219             {
220                 return hashSetOfT;
221             }
222
223             var listOfT = typeof(List<>).MakeGenericType(elementType);
224             if (requestedType.IsAssignableFrom(listOfT))
225             {
226                 return listOfT;
227             }
228
229             return null;
230         }
231
232         /// <summary>
233         /// Returns the Type object that should be used to identify the type in the o-space
234         /// metadata.  This is normally just the type that is passed in, but if the type
235         /// is a proxy that we have generated, then its base type is returned instead.
236         /// This ensures that both proxy entities and normal entities are treated as the
237         /// same kind of entity in the metadata and places where the metadata is used.
238         /// </summary>
239         internal static Type GetEntityIdentityType(Type entityType)
240         {
241             return EntityProxyFactory.IsProxyType(entityType) ? entityType.BaseType : entityType;
242         }
243
244         /// <summary>
245         /// Provides a standard helper method for quoting identifiers
246         /// </summary>
247         /// <param name="identifier">Identifier to be quoted. Does not validate that this identifier is valid.</param>
248         /// <returns>Quoted string</returns>
249         internal static string QuoteIdentifier(string identifier)
250         {
251             Debug.Assert(identifier != null, "identifier should not be null");
252             return "[" + identifier.Replace("]", "]]") + "]";
253         }
254
255         // The class contains functions that take the proper informational variables and then construct
256         // the appropriate exception with an error string obtained from the resource file.
257         // The exception is then returned to the caller, so that the caller may then throw from its
258         // location so that the catcher of the exception will have the appropriate call stack.
259         // This class is used so that there will be compile time checking of error messages.
260
261         static internal ArgumentException Argument(string error) {
262             return new ArgumentException(error);
263         }
264         static internal ArgumentException Argument(string error, Exception inner) {
265             return new ArgumentException(error, inner);
266         }
267         static internal ArgumentException Argument(string error, string parameter) {
268             return new ArgumentException(error, parameter);
269         }
270         static internal ArgumentException Argument(string error, string parameter, Exception inner) {
271             return new ArgumentException(error, parameter, inner);
272         }
273         static internal ArgumentNullException ArgumentNull(string parameter) {
274             return new ArgumentNullException(parameter);
275         }
276         static internal ArgumentOutOfRangeException ArgumentOutOfRange(string parameterName) {
277             return new ArgumentOutOfRangeException(parameterName);
278         }
279         static internal ArgumentOutOfRangeException ArgumentOutOfRange(string message, string parameterName) {
280             return new ArgumentOutOfRangeException(parameterName, message);
281         }
282         static internal EntityCommandExecutionException CommandExecution(string message) {
283             return new EntityCommandExecutionException(message);
284         }
285         static internal EntityCommandExecutionException CommandExecution(string message, Exception innerException) {
286             return new EntityCommandExecutionException(message, innerException);
287         }
288         static internal EntityCommandCompilationException CommandCompilation(string message, Exception innerException) {
289             return new EntityCommandCompilationException(message, innerException);
290         }
291         static internal PropertyConstraintException PropertyConstraint(string message, string propertyName)
292         {
293             return new PropertyConstraintException(message, propertyName);
294         }
295         static internal ConstraintException Constraint(string message)
296         {
297             return new ConstraintException(message);
298         }
299         static internal IndexOutOfRangeException IndexOutOfRange(string error)
300         {
301             return new IndexOutOfRangeException(error);
302         }
303         static internal InvalidOperationException InvalidOperation(string error) {
304             return new InvalidOperationException(error);
305         }
306         static internal InvalidOperationException InvalidOperation(string error, Exception inner) {
307             return new InvalidOperationException(error, inner);
308         }
309         static internal ArgumentException InvalidStringArgument(string parameterName) {
310             return Argument(System.Data.Entity.Strings.InvalidStringArgument(parameterName), parameterName);
311         }
312         static internal MappingException Mapping(string message)
313         {
314             return new MappingException(message);
315         }
316         static internal MetadataException Metadata(string message, Exception inner)
317         {
318             return new MetadataException(message, inner);
319         }
320         static internal MetadataException Metadata(string message)
321         {
322             return new MetadataException(message);
323         }
324         static internal NotSupportedException NotSupported()
325         {
326             return new NotSupportedException();
327         }
328         static internal NotSupportedException NotSupported(string error) {
329             return new NotSupportedException(error);
330         }
331         static internal ObjectDisposedException ObjectDisposed(string error) {
332             return new ObjectDisposedException(null, error);
333         }
334         static internal ObjectNotFoundException ObjectNotFound(string error) {
335             return new ObjectNotFoundException(error);
336         }
337
338         // SSDL Generator
339         //static internal StrongTypingException StrongTyping(string error, Exception innerException) {
340         //    StrongTypingException e = new StrongTypingException(error, innerException);
341         //    TraceExceptionAsReturnValue(e);
342         //    return e;
343         //}
344         #region Query Exceptions
345         /// <summary>
346         /// EntityException factory method
347         /// </summary>
348         /// <param name="message"></param>
349         /// <returns>EntityException</returns>
350         static internal EntitySqlException EntitySqlError( string message )
351         {
352             return new EntitySqlException(message);
353         }
354
355         /// <summary>
356         /// EntityException factory method
357         /// </summary>
358         /// <param name="message"></param>
359         /// <param name="innerException"></param>
360         /// <returns></returns>
361         static internal EntitySqlException EntitySqlError( string message, Exception innerException)
362         {
363             return new EntitySqlException(message, innerException);
364         }
365
366         /// <summary>
367         /// EntityException factory method
368         /// </summary>
369         /// <param name="errCtx"></param>
370         /// <param name="message"></param>
371         /// <returns>EntityException</returns>
372         static internal EntitySqlException EntitySqlError( System.Data.Common.EntitySql.ErrorContext errCtx, string message )
373         {
374             return EntitySqlException.Create(errCtx, message, null);
375         }
376
377         /// <summary>
378         /// EntityException factory method
379         /// </summary>
380         /// <param name="errCtx"></param>
381         /// <param name="message"></param>
382         /// <returns>EntityException</returns>
383         static internal EntitySqlException EntitySqlError( System.Data.Common.EntitySql.ErrorContext errCtx, string message, Exception innerException )
384         {
385             return EntitySqlException.Create(errCtx, message, null);
386         }
387
388         /// <summary>
389         /// EntityException factory method
390         /// </summary>
391         /// <param name="queryText"></param>
392         /// <param name="errorMessage"></param>
393         /// <param name="errorPosition"></param>
394         /// <returns></returns>
395         static internal EntitySqlException EntitySqlError( string queryText, string errorMessage, int errorPosition )
396         {
397             return EntitySqlException.Create(queryText, errorMessage, errorPosition, null, false, null);
398         }
399
400         /// <summary>
401         /// EntityException factory method. AdditionalErrorInformation will be used inlined if loadContextInfoFromResource is false.
402         /// </summary>
403         /// <param name="queryText"></param>
404         /// <param name="errorMessage"></param>
405         /// <param name="errorPosition"></param>
406         /// <param name="additionalErrorInformation"></param>
407         /// <param name="loadContextInfoFromResource"></param>
408         /// <returns></returns>
409         static internal EntitySqlException EntitySqlError( string queryText,
410                                                    string errorMessage,
411                                                    int errorPosition,
412                                                    string additionalErrorInformation,
413                                                    bool loadContextInfoFromResource )
414         {
415             return EntitySqlException.Create(queryText,
416                                                   errorMessage,
417                                                   errorPosition,
418                                                   additionalErrorInformation,
419                                                   loadContextInfoFromResource,
420                                                   null);
421         }
422         #endregion
423
424         #region Bridge Errors
425         static internal ProviderIncompatibleException CannotCloneStoreProvider() {
426             return ProviderIncompatible(System.Data.Entity.Strings.EntityClient_CannotCloneStoreProvider);
427         }
428         static internal InvalidOperationException ClosedDataReaderError() {
429             return InvalidOperation(System.Data.Entity.Strings.ADP_ClosedDataReaderError);
430         }
431         static internal InvalidOperationException DataReaderClosed(string method) {
432             return InvalidOperation(System.Data.Entity.Strings.ADP_DataReaderClosed(method));
433         }
434         static internal InvalidOperationException ImplicitlyClosedDataReaderError() {
435             return InvalidOperation(System.Data.Entity.Strings.ADP_ImplicitlyClosedDataReaderError);
436         }
437         static internal IndexOutOfRangeException InvalidBufferSizeOrIndex(int numBytes, int bufferIndex) {
438             return IndexOutOfRange(System.Data.Entity.Strings.ADP_InvalidBufferSizeOrIndex(numBytes.ToString(CultureInfo.InvariantCulture), bufferIndex.ToString(CultureInfo.InvariantCulture)));
439         }
440         static internal IndexOutOfRangeException InvalidDataLength(long length) {
441             return IndexOutOfRange(System.Data.Entity.Strings.ADP_InvalidDataLength(length.ToString(CultureInfo.InvariantCulture)));
442         }
443         static internal ArgumentOutOfRangeException InvalidDestinationBufferIndex(int maxLen, int dstOffset, string parameterName) {
444             return ArgumentOutOfRange(System.Data.Entity.Strings.ADP_InvalidDestinationBufferIndex(maxLen.ToString(CultureInfo.InvariantCulture), dstOffset.ToString(CultureInfo.InvariantCulture)), parameterName);
445         }
446         static internal ArgumentOutOfRangeException InvalidSourceBufferIndex(int maxLen, long srcOffset, string parameterName) {
447             return ArgumentOutOfRange(System.Data.Entity.Strings.ADP_InvalidSourceBufferIndex(maxLen.ToString(CultureInfo.InvariantCulture), srcOffset.ToString(CultureInfo.InvariantCulture)), parameterName);
448         }
449         static internal InvalidOperationException MustUseSequentialAccess() {
450             return InvalidOperation(System.Data.Entity.Strings.ADP_MustUseSequentialAccess);
451         }
452         static internal InvalidOperationException NoData() {
453             return InvalidOperation(System.Data.Entity.Strings.ADP_NoData);
454         }
455         static internal InvalidOperationException NonSequentialArrayOffsetAccess(long badIndex, long currIndex, string method) {
456             return InvalidOperation(System.Data.Entity.Strings.ADP_NonSequentialChunkAccess(badIndex.ToString(CultureInfo.InvariantCulture), currIndex.ToString(CultureInfo.InvariantCulture), method));
457         }
458         static internal InvalidOperationException NonSequentialColumnAccess(int badCol, int currCol) {
459             return InvalidOperation(System.Data.Entity.Strings.ADP_NonSequentialColumnAccess(badCol.ToString(CultureInfo.InvariantCulture), currCol.ToString(CultureInfo.InvariantCulture)));
460         }
461         static internal NotSupportedException KeysRequiredForJoinOverNest(Query.InternalTrees.Op op) {
462             return NotSupported(System.Data.Entity.Strings.ADP_KeysRequiredForJoinOverNest(op.OpType.ToString()));
463         }
464         static internal NotSupportedException KeysRequiredForNesting() {
465             return NotSupported(System.Data.Entity.Strings.ADP_KeysRequiredForNesting);
466         }
467         static internal NotSupportedException NestingNotSupported(Query.InternalTrees.Op parentOp, Query.InternalTrees.Op childOp) {
468             return NotSupported(System.Data.Entity.Strings.ADP_NestingNotSupported(parentOp.OpType.ToString(), childOp.OpType.ToString()));
469         }
470         static internal NotSupportedException ProviderDoesNotSupportCommandTrees() {
471             return NotSupported(System.Data.Entity.Strings.ADP_ProviderDoesNotSupportCommandTrees);
472         }
473         static internal EntityCommandExecutionException CommandExecutionDataReaderFieldCountForScalarType() {
474             return CommandExecution(System.Data.Entity.Strings.ADP_InvalidDataReaderFieldCountForScalarType);
475         }
476         static internal EntityCommandExecutionException CommandExecutionDataReaderMissingColumnForType(EdmMember member, EdmType currentType) {
477             return CommandExecution(System.Data.Entity.Strings.ADP_InvalidDataReaderMissingColumnForType(
478                 currentType.FullName, member.Name));
479         }
480         static internal EntityCommandExecutionException CommandExecutionDataReaderMissinDiscriminatorColumn(string columnName, EdmFunction functionImport) {
481             return CommandExecution(System.Data.Entity.Strings.ADP_InvalidDataReaderMissingDiscriminatorColumn(columnName, functionImport.FullName));
482         }
483
484         #endregion
485
486         #region EntityClient Errors
487         static internal ProviderIncompatibleException ProviderIncompatible(string error) {
488             return new ProviderIncompatibleException(error);
489         }
490         static internal ProviderIncompatibleException ProviderIncompatible(string error, Exception innerException) {
491             return new ProviderIncompatibleException(error, innerException);
492         }
493         static internal EntityException Provider(string error) {
494             return new EntityException(error);
495         }
496         static internal EntityException Provider(Exception inner) {
497             return new EntityException(System.Data.Entity.Strings.EntityClient_ProviderGeneralError, inner);
498         }
499         static internal EntityException Provider(string parameter, Exception inner) {
500             return new EntityException(System.Data.Entity.Strings.EntityClient_ProviderSpecificError(parameter), inner);
501         }
502         static internal EntityException ProviderExceptionWithMessage(string message, Exception inner) {
503             return new EntityException(message, inner);
504         }
505         #endregion //EntityClient Errors
506
507         #region SqlClient Errors
508
509         static internal InvalidOperationException SqlTypesAssemblyNotFound()
510         {
511             return InvalidOperation(System.Data.Entity.Strings.SqlProvider_SqlTypesAssemblyNotFound);
512         }
513
514         static internal ProviderIncompatibleException GeographyValueNotSqlCompatible()
515         {
516             return ProviderIncompatible(System.Data.Entity.Strings.SqlProvider_GeographyValueNotSqlCompatible);
517         }
518
519         static internal ProviderIncompatibleException GeometryValueNotSqlCompatible()
520         {
521             return ProviderIncompatible(System.Data.Entity.Strings.SqlProvider_GeometryValueNotSqlCompatible);
522         }
523
524         #endregion //SqlClient Errors
525
526         #region Metadata Errors
527         static internal MetadataException InvalidSchemaEncountered(string errors) {
528             // EntityRes.GetString implementation truncates the string arguments to a max length of 1024. 
529             // Since csdl, ssdl, providermanifest can have bunch of errors in them and we want to
530             // show all of them, we are using String.Format to form the error message.
531             // Using CurrentCulture since that's what EntityRes.GetString uses.
532             return Metadata(String.Format(CultureInfo.CurrentCulture, EntityRes.GetString(EntityRes.InvalidSchemaEncountered), errors));
533         }
534         static internal MetadataException InvalidCollectionForMapping(DataSpace space) {
535             return Metadata(System.Data.Entity.Strings.InvalidCollectionForMapping(space.ToString()));
536         }
537         // MemberCollection.cs
538         static internal ArgumentException MemberInvalidIdentity(string identity, string parameter) {
539             return Argument(System.Data.Entity.Strings.MemberInvalidIdentity(identity), parameter);
540         }
541         // MetadataCollection.cs
542         static internal ArgumentException ArrayTooSmall(string parameter) {
543             return Argument(System.Data.Entity.Strings.ArrayTooSmall, parameter);
544         }
545         static internal ArgumentException ItemDuplicateIdentity(string identity, string parameter, Exception inner) {
546             return Argument(System.Data.Entity.Strings.ItemDuplicateIdentity(identity), parameter, inner);
547         }
548         static internal ArgumentException ItemInvalidIdentity(string identity, string parameter) {
549             return Argument(System.Data.Entity.Strings.ItemInvalidIdentity(identity), parameter);
550         }
551         static internal InvalidOperationException MoreThanOneItemMatchesIdentity(string identity) {
552             return InvalidOperation(System.Data.Entity.Strings.MoreThanOneItemMatchesIdentity(identity));
553         }
554         static internal InvalidOperationException OperationOnReadOnlyCollection() {
555             return InvalidOperation(System.Data.Entity.Strings.OperationOnReadOnlyCollection);
556         }
557         // MetadataWorkspace.cs
558         static internal InvalidOperationException ItemCollectionAlreadyRegistered(DataSpace space) {
559             return InvalidOperation(System.Data.Entity.Strings.ItemCollectionAlreadyRegistered(space.ToString()));
560         }
561         static internal InvalidOperationException NoCollectionForSpace(DataSpace space) {
562             return InvalidOperation(System.Data.Entity.Strings.NoCollectionForSpace(space.ToString()));
563         }
564         static internal InvalidOperationException InvalidCollectionSpecified(DataSpace space) {
565             return InvalidOperation(System.Data.Entity.Strings.InvalidCollectionSpecified(space));
566         }
567         static internal MetadataException DifferentSchemaVersionInCollection(string itemCollectionType, double versionToRegister, double currentSchemaVersion)
568         {
569             return Metadata(Strings.DifferentSchemaVersionInCollection(itemCollectionType, versionToRegister, currentSchemaVersion));
570         }
571         // TypeUsage.cs
572         static internal ArgumentException NotBinaryTypeForTypeUsage() {
573             return Argument(System.Data.Entity.Strings.NotBinaryTypeForTypeUsage);
574         }
575         static internal ArgumentException NotDateTimeTypeForTypeUsage() {
576             return Argument(System.Data.Entity.Strings.NotDateTimeTypeForTypeUsage);
577         }
578         static internal ArgumentException NotDateTimeOffsetTypeForTypeUsage()
579         {
580             return Argument(System.Data.Entity.Strings.NotDateTimeOffsetTypeForTypeUsage);
581         }
582         static internal ArgumentException NotTimeTypeForTypeUsage()
583         {
584             return Argument(System.Data.Entity.Strings.NotTimeTypeForTypeUsage);
585         }
586         static internal ArgumentException NotDecimalTypeForTypeUsage() {
587             return Argument(System.Data.Entity.Strings.NotDecimalTypeForTypeUsage);
588         }
589         static internal ArgumentException NotStringTypeForTypeUsage() {
590             return Argument(System.Data.Entity.Strings.NotStringTypeForTypeUsage);
591         }
592         // EntityContainer.cs
593         static internal ArgumentException InvalidEntitySetName(string name) {
594             return Argument(System.Data.Entity.Strings.InvalidEntitySetName(name));
595         }
596         static internal ArgumentException InvalidRelationshipSetName(string name) {
597             return Argument(System.Data.Entity.Strings.InvalidRelationshipSetName(name));
598         }
599         static internal ArgumentException InvalidEDMVersion(double edmVersion)
600         {
601             return Argument(System.Data.Entity.Strings.InvalidEDMVersion(edmVersion.ToString(CultureInfo.CurrentCulture)));
602         }
603
604         // EntitySetBaseCollection.cs
605         static internal ArgumentException EntitySetInAnotherContainer(string parameter) {
606             return Argument(System.Data.Entity.Strings.EntitySetInAnotherContainer, parameter);
607         }
608         // util.cs
609         static internal InvalidOperationException OperationOnReadOnlyItem() {
610             return InvalidOperation(System.Data.Entity.Strings.OperationOnReadOnlyItem);
611         }
612         //FacetDescription.cs
613         static internal ArgumentException MinAndMaxValueMustBeSameForConstantFacet(string facetName, string typeName) {
614             return Argument(System.Data.Entity.Strings.MinAndMaxValueMustBeSameForConstantFacet(facetName, typeName));
615         }
616         static internal ArgumentException MissingDefaultValueForConstantFacet(string facetName, string typeName) {
617             return Argument(System.Data.Entity.Strings.MissingDefaultValueForConstantFacet(facetName, typeName));
618         }
619         static internal ArgumentException BothMinAndMaxValueMustBeSpecifiedForNonConstantFacet(string facetName, string typeName) {
620             return Argument(System.Data.Entity.Strings.BothMinAndMaxValueMustBeSpecifiedForNonConstantFacet(facetName, typeName));
621         }
622         static internal ArgumentException MinAndMaxValueMustBeDifferentForNonConstantFacet(string facetName, string typeName) {
623             return Argument(System.Data.Entity.Strings.MinAndMaxValueMustBeDifferentForNonConstantFacet(facetName, typeName));
624         }
625         static internal ArgumentException MinAndMaxMustBePositive(string facetName, string typeName) {
626             return Argument(System.Data.Entity.Strings.MinAndMaxMustBePositive(facetName, typeName));
627         }
628         static internal ArgumentException MinMustBeLessThanMax(string minimumValue, string facetName, string typeName) {
629             return Argument(System.Data.Entity.Strings.MinMustBeLessThanMax(minimumValue, facetName, typeName));
630         }
631         static internal ArgumentException EntitySetNotInCSpace(string name) {
632             return Argument(System.Data.Entity.Strings.EntitySetNotInCSPace(name));
633         }
634
635         static internal ArgumentException TypeNotInEntitySet(string entitySetName, string rootEntityTypeName, string entityTypeName) {
636             return Argument(System.Data.Entity.Strings.TypeNotInEntitySet(entityTypeName, rootEntityTypeName, entitySetName));
637         }
638
639         static internal ArgumentException AssociationSetNotInCSpace(string name) {
640             return Argument(System.Data.Entity.Strings.EntitySetNotInCSPace(name));
641         }
642
643         static internal ArgumentException TypeNotInAssociationSet(string setName, string rootEntityTypeName, string typeName) {
644             return Argument(System.Data.Entity.Strings.TypeNotInAssociationSet(typeName, rootEntityTypeName, setName));
645         }
646         #endregion //Metadata Errors
647
648         #region Internal Errors
649
650         // Internal error code to use with the InternalError exception.
651         //
652         // error numbers end up being hard coded in test cases; they can be removed, but should not be changed.
653         // reusing error numbers is probably OK, but not recommended.
654         //
655         // The acceptable range for this enum is
656         // 1000 - 1999
657         //
658         // The Range 10,000-15,000 is reserved for tools
659         //
660         /// You must never renumber these, because we rely upon them when
661         /// we get an exception report once we release the bits.
662         internal enum InternalErrorCode {
663             WrongNumberOfKeys = 1000,
664             UnknownColumnMapKind = 1001,
665             NestOverNest = 1002,
666             ColumnCountMismatch = 1003,
667
668             /// <summary>
669             /// Some assertion failed
670             /// </summary>
671             AssertionFailed = 1004,
672
673             UnknownVar = 1005,
674             WrongVarType = 1006,
675             ExtentWithoutEntity = 1007,
676             UnnestWithoutInput = 1008,
677             UnnestMultipleCollections = 1009,
678             CodeGen_NoSuchProperty = 1011,
679             JoinOverSingleStreamNest = 1012,
680             InvalidInternalTree = 1013,
681             NameValuePairNext = 1014,
682             InvalidParserState1 = 1015,
683             InvalidParserState2 = 1016,
684             /// <summary>
685             /// Thrown when SQL gen produces parameters for anything other than a 
686             /// modification command tree.
687             /// </summary>
688             SqlGenParametersNotPermitted = 1017,
689             EntityKeyMissingKeyValue = 1018,
690             /// <summary>
691             /// Thrown when an invalid data request is presented to a PropagatorResult in
692             /// the update pipeline (confusing simple/complex values, missing key values, etc.).
693             /// </summary>
694             UpdatePipelineResultRequestInvalid = 1019,
695             InvalidStateEntry = 1020,
696             /// <summary>
697             /// Thrown when the update pipeline encounters an invalid PrimitiveTypeKind
698             /// during a cast.
699             /// </summary>
700             InvalidPrimitiveTypeKind = 1021,
701             /// <summary>
702             /// Thrown when an unknown node type is encountered in ELinq expression translation.
703             /// </summary>
704             UnknownLinqNodeType = 1023,
705             /// <summary>
706             /// Thrown by result assembly upon encountering a collection column that does not use any columns
707             /// nor has a descriminated nested collection.
708             /// </summary>
709             CollectionWithNoColumns = 1024,
710             /// <summary>
711             /// Thrown when a lambda expression argument has an unexpected node type.
712             /// </summary>
713             UnexpectedLinqLambdaExpressionFormat = 1025,
714             /// <summary>
715             /// Thrown when a CommandTree is defined on a stored procedure EntityCommand instance.
716             /// </summary>
717             CommandTreeOnStoredProcedureEntityCommand = 1026,
718             /// <summary>
719             /// Thrown when an operation in the BoolExpr library is exceeding anticipated complexity.
720             /// </summary>
721             BoolExprAssert = 1027,
722             // AttemptToGenerateDefinitionForFunctionWithoutDef = 1028,
723             /// <summary>
724             /// Thrown when type A is promotable to type B, but ranking algorithm fails to rank the promotion.
725             /// </summary>
726             FailedToGeneratePromotionRank = 1029,
727         }
728
729         static internal Exception InternalError(InternalErrorCode internalError) {
730             return InvalidOperation(System.Data.Entity.Strings.ADP_InternalProviderError((int)internalError));
731         }
732
733         static internal Exception InternalError(InternalErrorCode internalError, int location, object additionalInfo) {
734             StringBuilder sb = new StringBuilder();
735             sb.AppendFormat("{0}, {1}", (int)internalError, location);
736             if (null != additionalInfo) {
737                 sb.AppendFormat(", {0}", additionalInfo);
738             }
739             return InvalidOperation(System.Data.Entity.Strings.ADP_InternalProviderError(sb.ToString()));
740         }
741
742         static internal Exception InternalError(InternalErrorCode internalError, int location) {
743             return InternalError(internalError, location, null);
744         }
745
746         #endregion
747
748         #region ObjectStateManager errors
749         internal static InvalidOperationException OriginalValuesDoesNotExist() {
750             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateEntry_OriginalValuesDoesNotExist);
751         }
752
753         internal static InvalidOperationException CurrentValuesDoesNotExist() {
754             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateEntry_CurrentValuesDoesNotExist);
755         }
756
757         internal static ArgumentException InvalidTypeForComplexTypeProperty(string argument) {
758             return EntityUtil.Argument(System.Data.Entity.Strings.ObjectStateEntry_InvalidTypeForComplexTypeProperty, argument);
759         }
760
761         internal static InvalidOperationException ObjectStateEntryinInvalidState() {
762             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateEntry_InvalidState);
763         }
764
765         internal static InvalidOperationException CantModifyDetachedDeletedEntries() {
766             throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateEntry_CantModifyDetachedDeletedEntries);
767         }
768         
769         internal static InvalidOperationException SetModifiedStates(string methodName)
770         {
771             throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateEntry_SetModifiedStates(methodName));
772         }
773
774         internal static InvalidOperationException EntityCantHaveMultipleChangeTrackers() {
775             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.Entity_EntityCantHaveMultipleChangeTrackers);
776         }
777
778         internal static InvalidOperationException CantModifyRelationValues() {
779             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateEntry_CantModifyRelationValues);
780         }
781
782         internal static InvalidOperationException CantModifyRelationState() {
783             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateEntry_CantModifyRelationState);
784         }
785
786         internal static InvalidOperationException CannotModifyKeyProperty(string fieldName) {
787             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateEntry_CannotModifyKeyProperty(fieldName));
788         }
789
790         internal static InvalidOperationException CantSetEntityKey() {
791             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateEntry_CantSetEntityKey);
792         }
793
794         internal static InvalidOperationException CannotAccessKeyEntryValues() {
795             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateEntry_CannotAccessKeyEntryValues);
796         }
797
798         internal static InvalidOperationException CannotModifyKeyEntryState() {
799             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateEntry_CannotModifyKeyEntryState);
800         }
801
802
803         internal static InvalidOperationException CannotCallDeleteOnKeyEntry() {
804             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateEntry_CannotDeleteOnKeyEntry);
805         }
806
807         internal static ArgumentException InvalidModifiedPropertyName(string propertyName) {
808             return EntityUtil.Argument(System.Data.Entity.Strings.ObjectStateEntry_SetModifiedOnInvalidProperty(propertyName));
809         }
810         internal static InvalidOperationException NoEntryExistForEntityKey() {
811             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateManager_NoEntryExistForEntityKey);
812         }
813         internal static ArgumentException DetachedObjectStateEntriesDoesNotExistInObjectStateManager() {
814             return EntityUtil.Argument(System.Data.Entity.Strings.ObjectStateManager_DetachedObjectStateEntriesDoesNotExistInObjectStateManager);
815         }
816
817         internal static InvalidOperationException ObjectStateManagerContainsThisEntityKey() {
818             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateManager_ObjectStateManagerContainsThisEntityKey);
819         }
820         internal static InvalidOperationException ObjectStateManagerDoesnotAllowToReAddUnchangedOrModifiedOrDeletedEntity(EntityState state) {
821             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateManager_DoesnotAllowToReAddUnchangedOrModifiedOrDeletedEntity(state));
822         }
823         internal static InvalidOperationException CannotFixUpKeyToExistingValues() {
824             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateManager_CannotFixUpKeyToExistingValues);
825         }
826         internal static InvalidOperationException KeyPropertyDoesntMatchValueInKey(bool forAttach)
827         {
828             if (forAttach)
829             {
830                 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateManager_KeyPropertyDoesntMatchValueInKeyForAttach);
831             }
832             else
833             {
834                 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateManager_KeyPropertyDoesntMatchValueInKey);
835             }
836         }
837
838         internal static void CheckValidStateForChangeEntityState(EntityState state)
839         {
840             switch(state)
841             {
842                 case EntityState.Added:
843                 case EntityState.Unchanged:
844                 case EntityState.Modified:
845                 case EntityState.Deleted:
846                 case EntityState.Detached:
847                     break;
848                 default:
849                     throw InvalidEntityStateArgument("state");
850             }
851         }
852
853         internal static void CheckValidStateForChangeRelationshipState(EntityState state, string paramName)
854         {
855             switch (state)
856             {
857                 case EntityState.Added:
858                 case EntityState.Unchanged:
859                 case EntityState.Deleted:
860                 case EntityState.Detached:
861                     break;
862                 default:
863                     throw InvalidRelationshipStateArgument(paramName);
864             }
865         }
866
867         internal static InvalidOperationException InvalidKey() {
868             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateManager_InvalidKey);
869         }
870         internal static InvalidOperationException AcceptChangesEntityKeyIsNotValid() {
871             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateManager_AcceptChangesEntityKeyIsNotValid);
872         }
873         internal static InvalidOperationException EntityConflictsWithKeyEntry() {
874             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateManager_EntityConflictsWithKeyEntry);
875         }
876         internal static InvalidOperationException ObjectDoesNotHaveAKey(object entity) {
877             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateManager_GetEntityKeyRequiresObjectToHaveAKey(entity.GetType().FullName));
878         }
879         internal static InvalidOperationException EntityValueChangedWithoutEntityValueChanging() {
880             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateEntry_EntityMemberChangedWithoutEntityMemberChanging);
881         }
882         internal static InvalidOperationException ChangedInDifferentStateFromChanging(EntityState currentState, EntityState previousState) {
883             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateEntry_ChangedInDifferentStateFromChanging(previousState, currentState));
884         }
885         internal static ArgumentException ChangeOnUnmappedProperty(string entityPropertyName) {
886             return EntityUtil.Argument(System.Data.Entity.Strings.ObjectStateEntry_ChangeOnUnmappedProperty(entityPropertyName));
887         }
888
889         internal static ArgumentException ChangeOnUnmappedComplexProperty(string complexPropertyName) {
890             return EntityUtil.Argument(System.Data.Entity.Strings.ObjectStateEntry_ChangeOnUnmappedComplexProperty(complexPropertyName));
891         }
892
893         internal static ArgumentException EntityTypeDoesNotMatchEntitySet(string entityType, string entitysetName, string argument) {
894             return Argument(System.Data.Entity.Strings.ObjectStateManager_EntityTypeDoesnotMatchtoEntitySetType(entityType, entitysetName), argument);
895         }
896         internal static InvalidOperationException NoEntryExistsForObject(object entity)
897         {
898             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateManager_NoEntryExistsForObject(entity.GetType().FullName));
899         }
900         internal static InvalidOperationException EntityNotTracked()
901         {
902             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateManager_EntityNotTracked);
903         }
904         internal static InvalidOperationException SetOriginalComplexProperties(string propertyName)
905         {
906             return InvalidOperation(Strings.ObjectStateEntry_SetOriginalComplexProperties(propertyName));
907         }
908         internal static InvalidOperationException NullOriginalValueForNonNullableProperty(string propertyName, string clrMemberName, string clrTypeName)
909         {
910             return InvalidOperation(Strings.ObjectStateEntry_NullOriginalValueForNonNullableProperty(propertyName, clrMemberName, clrTypeName));
911         }
912         internal static InvalidOperationException SetOriginalPrimaryKey(string propertyName)
913         {
914             return InvalidOperation(Strings.ObjectStateEntry_SetOriginalPrimaryKey(propertyName));
915         }
916
917         #endregion
918
919         #region ObjectMaterializer errors
920
921         internal static void ThrowPropertyIsNotNullable(string propertyName)
922         {
923             if (String.IsNullOrEmpty(propertyName))
924             {
925
926                 throw EntityUtil.Constraint(
927                   System.Data.Entity.Strings.Materializer_PropertyIsNotNullable);
928             }
929             else
930             {
931                 throw EntityUtil.PropertyConstraint(
932                     System.Data.Entity.Strings.Materializer_PropertyIsNotNullableWithName(propertyName), propertyName);
933             }
934         }
935
936         internal static void ThrowSetInvalidValue(object value, Type destinationType, string className, string propertyName)
937         {
938             if (null == value)
939             {
940                 throw EntityUtil.Constraint(
941                     System.Data.Entity.Strings.Materializer_SetInvalidValue(
942                         (Nullable.GetUnderlyingType(destinationType) ?? destinationType).Name,
943                         className, propertyName, "null"));
944             }
945             else
946             {
947                 throw EntityUtil.InvalidOperation(
948                     System.Data.Entity.Strings.Materializer_SetInvalidValue(
949                         (Nullable.GetUnderlyingType(destinationType) ?? destinationType).Name,
950                         className, propertyName, value.GetType().Name));
951             }
952         }        
953         internal static InvalidOperationException ValueInvalidCast(Type valueType, Type destinationType)
954         {
955             Debug.Assert(null != valueType, "null valueType");
956             Debug.Assert(null != destinationType, "null destinationType");
957             if (destinationType.IsValueType && destinationType.IsGenericType && (typeof(Nullable<>) == destinationType.GetGenericTypeDefinition()))
958             {
959                 return EntityUtil.InvalidOperation(
960                     System.Data.Entity.Strings.Materializer_InvalidCastNullable(
961                         valueType, destinationType.GetGenericArguments()[0]));
962             }
963             else
964             {
965                 return EntityUtil.InvalidOperation(
966                     System.Data.Entity.Strings.Materializer_InvalidCastReference(
967                         valueType, destinationType));
968             }
969         }
970         internal static InvalidOperationException ValueNullReferenceCast(Type destinationType)
971         {
972             Debug.Assert(null != destinationType, "null value");
973             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.Materializer_NullReferenceCast(destinationType.Name));
974         }
975
976         internal static NotSupportedException RecyclingEntity(EntityKey key, Type newEntityType, Type existingEntityType) {
977             return NotSupported(System.Data.Entity.Strings.Materializer_RecyclingEntity(System.Data.Common.TypeHelpers.GetFullName(key.EntityContainerName, key.EntitySetName), newEntityType.FullName, existingEntityType.FullName, key.ConcatKeyValue()));
978         }
979         internal static InvalidOperationException AddedEntityAlreadyExists(EntityKey key) {
980             return InvalidOperation(System.Data.Entity.Strings.Materializer_AddedEntityAlreadyExists(key.ConcatKeyValue()));
981         }
982         internal static InvalidOperationException CannotReEnumerateQueryResults() {
983             return InvalidOperation(System.Data.Entity.Strings.Materializer_CannotReEnumerateQueryResults);
984         }
985         internal static NotSupportedException MaterializerUnsupportedType() {
986             return NotSupported(System.Data.Entity.Strings.Materializer_UnsupportedType);
987         }
988         #endregion
989
990         #region ObjectView errors
991         internal static InvalidOperationException CannotReplacetheEntityorRow() {
992             return InvalidOperation(System.Data.Entity.Strings.ObjectView_CannotReplacetheEntityorRow);
993         }
994         internal static NotSupportedException IndexBasedInsertIsNotSupported() {
995             return NotSupported(System.Data.Entity.Strings.ObjectView_IndexBasedInsertIsNotSupported);
996         }
997         internal static InvalidOperationException WriteOperationNotAllowedOnReadOnlyBindingList() {
998             return InvalidOperation(System.Data.Entity.Strings.ObjectView_WriteOperationNotAllowedOnReadOnlyBindingList);
999         }
1000         internal static InvalidOperationException AddNewOperationNotAllowedOnAbstractBindingList() {
1001             return InvalidOperation(System.Data.Entity.Strings.ObjectView_AddNewOperationNotAllowedOnAbstractBindingList);
1002         }
1003         internal static ArgumentException IncompatibleArgument() {
1004             return Argument(System.Data.Entity.Strings.ObjectView_IncompatibleArgument);
1005         }
1006         internal static InvalidOperationException CannotResolveTheEntitySetforGivenEntity(Type type) {
1007             return InvalidOperation(System.Data.Entity.Strings.ObjectView_CannotResolveTheEntitySet(type.FullName));
1008         }
1009         
1010
1011         #endregion
1012        
1013
1014         #region EntityCollection Errors
1015         internal static InvalidOperationException NoRelationshipSetMatched(string relationshipName) {
1016             Debug.Assert(!String.IsNullOrEmpty(relationshipName), "empty relationshipName");
1017             return InvalidOperation(System.Data.Entity.Strings.Collections_NoRelationshipSetMatched(relationshipName));
1018         }        
1019         internal static InvalidOperationException ExpectedCollectionGotReference(string typeName, string roleName, string relationshipName) {
1020             return InvalidOperation(System.Data.Entity.Strings.Collections_ExpectedCollectionGotReference(typeName, roleName, relationshipName));
1021         }
1022         internal static InvalidOperationException CannotFillTryDifferentMergeOption(string relationshipName, string roleName) {
1023             return InvalidOperation(Strings.Collections_CannotFillTryDifferentMergeOption(relationshipName, roleName));
1024         }
1025         internal static InvalidOperationException CannotRemergeCollections() {
1026             return InvalidOperation(System.Data.Entity.Strings.Collections_UnableToMergeCollections);
1027         }
1028         internal static InvalidOperationException ExpectedReferenceGotCollection(string typeName, string roleName, string relationshipName) {
1029             return InvalidOperation(System.Data.Entity.Strings.EntityReference_ExpectedReferenceGotCollection(typeName, roleName, relationshipName));
1030         }
1031         internal static InvalidOperationException CannotAddMoreThanOneEntityToEntityReference(string roleName, string relationshipName) {
1032             return InvalidOperation(System.Data.Entity.Strings.EntityReference_CannotAddMoreThanOneEntityToEntityReference(roleName, relationshipName));
1033         }
1034         internal static ArgumentException CannotSetSpecialKeys() {
1035             return Argument(System.Data.Entity.Strings.EntityReference_CannotSetSpecialKeys, "value");
1036         }
1037         internal static InvalidOperationException EntityKeyValueMismatch() {
1038             return InvalidOperation(System.Data.Entity.Strings.EntityReference_EntityKeyValueMismatch);
1039         }
1040         internal static InvalidOperationException RelatedEndNotAttachedToContext(string relatedEndType) {
1041             return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_RelatedEndNotAttachedToContext(relatedEndType));
1042         }
1043         internal static InvalidOperationException CannotCreateRelationshipBetweenTrackedAndNoTrackedEntities(string roleName) {
1044             return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_CannotCreateRelationshipBetweenTrackedAndNoTrackedEntities(roleName));
1045         }
1046         internal static InvalidOperationException CannotCreateRelationshipEntitiesInDifferentContexts() {
1047             return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_CannotCreateRelationshipEntitiesInDifferentContexts);
1048         }
1049         internal static InvalidOperationException InvalidContainedTypeCollection(string entityType, string relatedEndType) {
1050             return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_InvalidContainedType_Collection(entityType, relatedEndType));
1051         }
1052         internal static InvalidOperationException InvalidContainedTypeReference(string entityType, string relatedEndType) {
1053             return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_InvalidContainedType_Reference(entityType, relatedEndType));
1054         }
1055         internal static InvalidOperationException CannotAddToFixedSizeArray(object collectionType) {
1056             return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_CannotAddToFixedSizeArray(collectionType.GetType()));
1057         }
1058         internal static InvalidOperationException CannotRemoveFromFixedSizeArray(object collectionType) {
1059             return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_CannotRemoveFromFixedSizeArray(collectionType.GetType()));
1060         }
1061         internal static InvalidOperationException OwnerIsNull() {
1062             return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_OwnerIsNull);
1063         }
1064         internal static InvalidOperationException UnableToAddRelationshipWithDeletedEntity() {
1065             return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_UnableToAddRelationshipWithDeletedEntity);
1066         }
1067         internal static InvalidOperationException ConflictingChangeOfRelationshipDetected() {
1068             return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_ConflictingChangeOfRelationshipDetected);
1069         }
1070         internal static InvalidOperationException InvalidRelationshipFixupDetected(string propertyName, string entityType) {
1071             return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_InvalidRelationshipFixupDetected(propertyName, entityType));
1072         }
1073         internal static InvalidOperationException LessThanExpectedRelatedEntitiesFound()
1074         {
1075             return InvalidOperation(System.Data.Entity.Strings.EntityReference_LessThanExpectedRelatedEntitiesFound);
1076         }
1077         internal static InvalidOperationException MoreThanExpectedRelatedEntitiesFound() {
1078             return InvalidOperation(System.Data.Entity.Strings.EntityReference_MoreThanExpectedRelatedEntitiesFound);
1079         }
1080         internal static InvalidOperationException CannotChangeReferentialConstraintProperty() {
1081             return InvalidOperation(System.Data.Entity.Strings.EntityReference_CannotChangeReferentialConstraintProperty);
1082         }
1083         internal static InvalidOperationException RelatedEndNotFound() {
1084             return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_RelatedEndNotFound);
1085         }
1086         internal static InvalidOperationException LoadCalledOnNonEmptyNoTrackedRelatedEnd() {
1087             return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_LoadCalledOnNonEmptyNoTrackedRelatedEnd);
1088         }
1089         internal static InvalidOperationException LoadCalledOnAlreadyLoadedNoTrackedRelatedEnd() {
1090             return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_LoadCalledOnAlreadyLoadedNoTrackedRelatedEnd);
1091         }   
1092         internal static InvalidOperationException MismatchedMergeOptionOnLoad(MergeOption mergeOption) {
1093             return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_MismatchedMergeOptionOnLoad(mergeOption));
1094         }
1095         internal static InvalidOperationException EntitySetIsNotValidForRelationship(string entitySetContainerName, string entitySetName, string roleName, string associationSetContainerName, string associationSetName) {
1096             return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_EntitySetIsNotValidForRelationship(entitySetContainerName, entitySetName, roleName, associationSetContainerName, associationSetName));
1097         }
1098         internal static InvalidOperationException UnableToRetrieveReferentialConstraintProperties() {
1099             return InvalidOperation(System.Data.Entity.Strings.RelationshipManager_UnableToRetrieveReferentialConstraintProperties);
1100         }
1101         internal static InvalidOperationException InconsistentReferentialConstraintProperties() {
1102             return InvalidOperation(System.Data.Entity.Strings.RelationshipManager_InconsistentReferentialConstraintProperties);
1103         }
1104         internal static InvalidOperationException CircularRelationshipsWithReferentialConstraints() {
1105             return InvalidOperation(System.Data.Entity.Strings.RelationshipManager_CircularRelationshipsWithReferentialConstraints);
1106         }
1107         internal static ArgumentException UnableToFindRelationshipTypeInMetadata(string relationshipName, string parameterName) {
1108             return Argument(System.Data.Entity.Strings.RelationshipManager_UnableToFindRelationshipTypeInMetadata(relationshipName), parameterName);
1109         }
1110         internal static ArgumentException InvalidTargetRole(string relationshipName, string targetRoleName, string parameterName) {
1111             return Argument(System.Data.Entity.Strings.RelationshipManager_InvalidTargetRole(relationshipName, targetRoleName), parameterName);
1112         }
1113         internal static InvalidOperationException OwnerIsNotSourceType(string ownerType, string sourceRoleType, string sourceRoleName, string relationshipName) {
1114             return InvalidOperation(System.Data.Entity.Strings.RelationshipManager_OwnerIsNotSourceType(ownerType, sourceRoleType, sourceRoleName, relationshipName));
1115         }                
1116         internal static InvalidOperationException UnexpectedNullContext() {
1117             return InvalidOperation(System.Data.Entity.Strings.RelationshipManager_UnexpectedNullContext);
1118         }
1119         internal static InvalidOperationException ReferenceAlreadyInitialized() {
1120             return InvalidOperation(System.Data.Entity.Strings.RelationshipManager_ReferenceAlreadyInitialized(System.Data.Entity.Strings.RelationshipManager_InitializeIsForDeserialization));
1121         }        
1122         internal static InvalidOperationException RelationshipManagerAttached() {
1123             return InvalidOperation(System.Data.Entity.Strings.RelationshipManager_RelationshipManagerAttached(System.Data.Entity.Strings.RelationshipManager_InitializeIsForDeserialization));
1124         }
1125         internal static InvalidOperationException CollectionAlreadyInitialized() {
1126             return InvalidOperation(System.Data.Entity.Strings.RelationshipManager_CollectionAlreadyInitialized(System.Data.Entity.Strings.RelationshipManager_CollectionInitializeIsForDeserialization));
1127         }
1128         internal static InvalidOperationException CollectionRelationshipManagerAttached() {
1129             return InvalidOperation(System.Data.Entity.Strings.RelationshipManager_CollectionRelationshipManagerAttached(System.Data.Entity.Strings.RelationshipManager_CollectionInitializeIsForDeserialization));
1130         }
1131         internal static void CheckContextNull(ObjectContext context)
1132         {
1133             if ((object)context == null)
1134             {
1135                 throw EntityUtil.UnexpectedNullContext();
1136             }
1137         }
1138
1139         internal static void CheckArgumentMergeOption(MergeOption mergeOption) {
1140             switch(mergeOption) {
1141             case MergeOption.NoTracking:
1142             case MergeOption.AppendOnly:
1143             case MergeOption.OverwriteChanges:
1144             case MergeOption.PreserveChanges:
1145                 break;
1146             default:
1147                 throw EntityUtil.InvalidMergeOption(mergeOption);
1148             }
1149         }
1150         internal static void CheckArgumentRefreshMode(RefreshMode refreshMode) {
1151             switch(refreshMode) {
1152             case RefreshMode.ClientWins:
1153             case RefreshMode.StoreWins:
1154                 break;
1155             default:
1156                 throw EntityUtil.InvalidRefreshMode(refreshMode);
1157             }
1158         }
1159         internal static InvalidOperationException InvalidEntityStateSource() {
1160             return InvalidOperation(System.Data.Entity.Strings.Collections_InvalidEntityStateSource);
1161         }
1162         internal static InvalidOperationException InvalidEntityStateLoad(string relatedEndType) {
1163             return InvalidOperation(System.Data.Entity.Strings.Collections_InvalidEntityStateLoad(relatedEndType));
1164             }
1165         internal static InvalidOperationException InvalidOwnerStateForAttach() {
1166             return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_InvalidOwnerStateForAttach);
1167         }
1168         internal static InvalidOperationException InvalidNthElementNullForAttach(int index) {
1169             return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_InvalidNthElementNullForAttach(index));
1170         }
1171         internal static InvalidOperationException InvalidNthElementContextForAttach(int index) {
1172             return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_InvalidNthElementContextForAttach(index));
1173         }
1174         internal static InvalidOperationException InvalidNthElementStateForAttach(int index) {
1175             return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_InvalidNthElementStateForAttach(index));
1176         }
1177         internal static InvalidOperationException InvalidEntityContextForAttach() {
1178             return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_InvalidEntityContextForAttach);
1179         }
1180         internal static InvalidOperationException InvalidEntityStateForAttach() {
1181             return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_InvalidEntityStateForAttach);
1182         }
1183         internal static InvalidOperationException UnableToAddToDisconnectedRelatedEnd() {
1184             return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_UnableToAddEntity);
1185         }
1186         internal static InvalidOperationException UnableToRemoveFromDisconnectedRelatedEnd() {
1187             return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_UnableToRemoveEntity);
1188         }
1189         internal static InvalidOperationException ProxyMetadataIsUnavailable(Type type, Exception inner) {
1190             return InvalidOperation(System.Data.Entity.Strings.EntityProxyTypeInfo_ProxyMetadataIsUnavailable(type.FullName), inner);
1191         }
1192         internal static InvalidOperationException DuplicateTypeForProxyType(Type type) {
1193             return InvalidOperation(System.Data.Entity.Strings.EntityProxyTypeInfo_DuplicateOSpaceType(type.FullName));
1194         }
1195         #endregion
1196
1197         #region ObjectContext errors
1198         internal static InvalidOperationException ClientEntityRemovedFromStore(string entitiesKeys) {
1199             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectContext_ClientEntityRemovedFromStore(entitiesKeys));
1200         }
1201         internal static InvalidOperationException StoreEntityNotPresentInClient() {
1202             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectContext_StoreEntityNotPresentInClient);
1203         }
1204         internal static InvalidOperationException ContextMetadataHasChanged() {
1205             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectContext_MetadataHasChanged);
1206         }
1207         internal static ArgumentException InvalidConnection(bool isConnectionConstructor, Exception innerException)
1208         {
1209             if (isConnectionConstructor)
1210             {
1211                 return InvalidConnection("connection", innerException);
1212             }
1213             else
1214             {
1215                 return InvalidConnectionString("connectionString", innerException);
1216             }
1217         }
1218         internal static ArgumentException InvalidConnectionString(string parameter, Exception inner) {
1219             return EntityUtil.Argument(System.Data.Entity.Strings.ObjectContext_InvalidConnectionString, parameter, inner);
1220         }
1221         internal static ArgumentException InvalidConnection(string parameter, Exception inner) {
1222             return EntityUtil.Argument(System.Data.Entity.Strings.ObjectContext_InvalidConnection, parameter, inner);
1223         }
1224         internal static InvalidOperationException InvalidDataAdapter() {
1225             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectContext_InvalidDataAdapter);
1226         }
1227         internal static ArgumentException InvalidDefaultContainerName(string parameter, string defaultContainerName) {
1228             return EntityUtil.Argument(System.Data.Entity.Strings.ObjectContext_InvalidDefaultContainerName(defaultContainerName), parameter);
1229         }
1230         internal static InvalidOperationException NthElementInAddedState(int i) {
1231             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectContext_NthElementInAddedState(i));
1232         }
1233         internal static InvalidOperationException NthElementIsDuplicate(int i) {
1234             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectContext_NthElementIsDuplicate(i));
1235         }
1236         internal static InvalidOperationException NthElementIsNull(int i) {
1237             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectContext_NthElementIsNull(i));
1238         }
1239         internal static InvalidOperationException NthElementNotInObjectStateManager(int i) {
1240             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectContext_NthElementNotInObjectStateManager(i));
1241         }
1242         internal static ObjectDisposedException ObjectContextDisposed() {
1243             return EntityUtil.ObjectDisposed(System.Data.Entity.Strings.ObjectContext_ObjectDisposed);
1244         }
1245         internal static ObjectNotFoundException ObjectNotFound() {
1246             return EntityUtil.ObjectNotFound(System.Data.Entity.Strings.ObjectContext_ObjectNotFound);
1247         }
1248         internal static InvalidOperationException InvalidEntityType(Type type) {
1249             Debug.Assert(type != null, "The type cannot be null.");
1250             return InvalidOperation(System.Data.Entity.Strings.ObjectContext_NoMappingForEntityType(type.FullName));
1251         }
1252         internal static InvalidOperationException CannotDeleteEntityNotInObjectStateManager() {
1253             return InvalidOperation(System.Data.Entity.Strings.ObjectContext_CannotDeleteEntityNotInObjectStateManager);
1254         }
1255         internal static InvalidOperationException CannotDetachEntityNotInObjectStateManager() {
1256             return InvalidOperation(System.Data.Entity.Strings.ObjectContext_CannotDetachEntityNotInObjectStateManager);
1257         }
1258         internal static InvalidOperationException EntitySetNotFoundForName(string entitySetName) {
1259             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectContext_EntitySetNotFoundForName(entitySetName));
1260         }
1261         internal static InvalidOperationException EntityContainterNotFoundForName(string entityContainerName) {
1262             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectContext_EntityContainerNotFoundForName(entityContainerName));
1263         }
1264         internal static ArgumentException InvalidCommandTimeout(string argument) {
1265             return Argument(System.Data.Entity.Strings.ObjectContext_InvalidCommandTimeout, argument);
1266         }
1267         internal static InvalidOperationException EntityAlreadyExistsInObjectStateManager() {
1268             return InvalidOperation(System.Data.Entity.Strings.ObjectContext_EntityAlreadyExistsInObjectStateManager);
1269         }
1270         internal static InvalidOperationException InvalidEntitySetInKey(string keyContainer, string keyEntitySet, string expectedContainer, string expectedEntitySet) {
1271             return InvalidOperation(System.Data.Entity.Strings.ObjectContext_InvalidEntitySetInKey(keyContainer, keyEntitySet, expectedContainer, expectedEntitySet));
1272         }
1273         internal static InvalidOperationException InvalidEntitySetInKeyFromName(string keyContainer, string keyEntitySet, string expectedContainer, string expectedEntitySet, string argument) {
1274             return InvalidOperation(System.Data.Entity.Strings.ObjectContext_InvalidEntitySetInKeyFromName(keyContainer, keyEntitySet, expectedContainer, expectedEntitySet, argument));
1275         }
1276         internal static InvalidOperationException CannotAttachEntityWithoutKey() {
1277             return InvalidOperation(System.Data.Entity.Strings.ObjectContext_CannotAttachEntityWithoutKey);
1278         }
1279         internal static InvalidOperationException CannotAttachEntityWithTemporaryKey() {
1280             return InvalidOperation(System.Data.Entity.Strings.ObjectContext_CannotAttachEntityWithTemporaryKey);
1281         }
1282         internal static InvalidOperationException EntitySetNameOrEntityKeyRequired() {
1283             return InvalidOperation(System.Data.Entity.Strings.ObjectContext_EntitySetNameOrEntityKeyRequired);
1284         }
1285         internal static InvalidOperationException ExecuteFunctionTypeMismatch(Type typeArgument, EdmType expectedElementType) {
1286             return InvalidOperation(System.Data.Entity.Strings.ObjectContext_ExecuteFunctionTypeMismatch(
1287                 typeArgument.FullName,
1288                 expectedElementType.FullName));
1289         }
1290         internal static InvalidOperationException ExecuteFunctionCalledWithNonReaderFunction(EdmFunction functionImport) {
1291             // report ExecuteNonQuery return type if no explicit return type is given
1292             string message;
1293             if (null == functionImport.ReturnParameter)
1294             {
1295                 message = System.Data.Entity.Strings.ObjectContext_ExecuteFunctionCalledWithNonQueryFunction(
1296                     functionImport.Name);
1297             }
1298             else
1299             {
1300                 message = System.Data.Entity.Strings.ObjectContext_ExecuteFunctionCalledWithScalarFunction(
1301                     functionImport.ReturnParameter.TypeUsage.EdmType.FullName, functionImport.Name);
1302             }
1303             return InvalidOperation(message);
1304         }        
1305         internal static ArgumentException QualfiedEntitySetName(string parameterName) {
1306             return Argument(System.Data.Entity.Strings.ObjectContext_QualfiedEntitySetName, parameterName);
1307         }
1308         internal static ArgumentException ContainerQualifiedEntitySetNameRequired(string argument) {
1309             return Argument(System.Data.Entity.Strings.ObjectContext_ContainerQualifiedEntitySetNameRequired, argument);
1310         }
1311         internal static InvalidOperationException CannotSetDefaultContainerName() {
1312             return InvalidOperation(System.Data.Entity.Strings.ObjectContext_CannotSetDefaultContainerName);
1313         }
1314         internal static ArgumentException EntitiesHaveDifferentType(string originalEntityTypeName, string changedEntityTypeName) {
1315             return Argument(System.Data.Entity.Strings.ObjectContext_EntitiesHaveDifferentType(originalEntityTypeName, changedEntityTypeName));
1316         }
1317         internal static InvalidOperationException EntityMustBeUnchangedOrModified(EntityState state) {
1318             return InvalidOperation(System.Data.Entity.Strings.ObjectContext_EntityMustBeUnchangedOrModified(state.ToString()));
1319         }
1320         internal static InvalidOperationException EntityMustBeUnchangedOrModifiedOrDeleted(EntityState state) {
1321             return InvalidOperation(System.Data.Entity.Strings.ObjectContext_EntityMustBeUnchangedOrModifiedOrDeleted(state.ToString()));
1322         }
1323         internal static InvalidOperationException EntityNotTrackedOrHasTempKey()
1324         {
1325             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectContext_EntityNotTrackedOrHasTempKey);
1326         }
1327
1328         internal static InvalidOperationException AcceptAllChangesFailure(Exception e) {
1329             return InvalidOperation(System.Data.Entity.Strings.ObjectContext_AcceptAllChangesFailure(e.Message));
1330         }
1331         internal static ArgumentException InvalidEntitySetOnEntity(string entitySetName, Type entityType, string parameter) {
1332             return Argument(System.Data.Entity.Strings.ObjectContext_InvalidEntitySetOnEntity(entitySetName, entityType), parameter);
1333         }
1334         internal static ArgumentException InvalidEntityTypeForObjectSet(string tEntityType, string entitySetType, string entitySetName, string parameter) {
1335             return Argument(System.Data.Entity.Strings.ObjectContext_InvalidObjectSetTypeForEntitySet(tEntityType, entitySetType, entitySetName), parameter);
1336         }
1337         internal static InvalidOperationException RequiredMetadataNotAvailable() {
1338             return InvalidOperation(System.Data.Entity.Strings.ObjectContext_RequiredMetadataNotAvailble);
1339         }
1340
1341         internal static ArgumentException MultipleEntitySetsFoundInSingleContainer(string entityTypeName, string entityContainerName, string exceptionParameterName) {
1342             return Argument(System.Data.Entity.Strings.ObjectContext_MultipleEntitySetsFoundInSingleContainer(entityTypeName, entityContainerName), exceptionParameterName);
1343         }
1344
1345         internal static ArgumentException MultipleEntitySetsFoundInAllContainers(string entityTypeName, string exceptionParameterName) {
1346             return Argument(System.Data.Entity.Strings.ObjectContext_MultipleEntitySetsFoundInAllContainers(entityTypeName), exceptionParameterName);
1347         }
1348
1349         internal static ArgumentException NoEntitySetFoundForType(string entityTypeName, string exceptionParameterName) {
1350             return Argument(System.Data.Entity.Strings.ObjectContext_NoEntitySetFoundForType(entityTypeName), exceptionParameterName);
1351         }
1352         internal static InvalidOperationException EntityNotInObjectSet_Delete(string actualContainerName, string actualEntitySetName, string expectedContainerName, string expectedEntitySetName) {
1353             return InvalidOperation(System.Data.Entity.Strings.ObjectContext_EntityNotInObjectSet_Delete(actualContainerName, actualEntitySetName, expectedContainerName, expectedEntitySetName));
1354         }
1355
1356         internal static InvalidOperationException EntityNotInObjectSet_Detach(string actualContainerName, string actualEntitySetName, string expectedContainerName, string expectedEntitySetName) {
1357             return InvalidOperation(System.Data.Entity.Strings.ObjectContext_EntityNotInObjectSet_Detach(actualContainerName, actualEntitySetName, expectedContainerName, expectedEntitySetName));
1358         }
1359
1360         internal static ArgumentException InvalidRelationshipStateArgument(string paramName)
1361         {
1362             return new ArgumentException(Strings.ObjectContext_InvalidRelationshipState, paramName);
1363         }
1364
1365         internal static ArgumentException InvalidEntityStateArgument(string paramName)
1366         {
1367             return new ArgumentException(Strings.ObjectContext_InvalidEntityState, paramName);
1368         }
1369
1370         #endregion
1371
1372         #region Complex Types Errors
1373         // Complex types exceptions
1374         internal static InvalidOperationException NullableComplexTypesNotSupported(string propertyName)
1375         {
1376             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ComplexObject_NullableComplexTypesNotSupported(propertyName));
1377         }
1378         internal static InvalidOperationException ComplexObjectAlreadyAttachedToParent()
1379         {
1380             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ComplexObject_ComplexObjectAlreadyAttachedToParent);
1381         }
1382         internal static ArgumentException ComplexChangeRequestedOnScalarProperty(string propertyName)
1383         {
1384             return EntityUtil.Argument(System.Data.Entity.Strings.ComplexObject_ComplexChangeRequestedOnScalarProperty(propertyName));
1385         }
1386         #endregion
1387
1388         internal static ArgumentException SpanPathSyntaxError() {
1389             return Argument(System.Data.Entity.Strings.ObjectQuery_Span_SpanPathSyntaxError);
1390         }
1391
1392         /// <summary>
1393         /// This is only used for Include path argument, thus the parameter name is hardcoded to "path"
1394         /// </summary>
1395         /// <returns></returns>
1396         static internal ArgumentException ADP_InvalidMultipartNameDelimiterUsage()
1397         {
1398             return Argument(System.Data.Entity.Strings.ADP_InvalidMultipartNameDelimiterUsage, "path");
1399         }
1400
1401         static internal Exception InvalidConnectionOptionValue(string key) 
1402         {
1403             return Argument(System.Data.Entity.Strings.ADP_InvalidConnectionOptionValue(key));
1404         }
1405
1406         static internal ArgumentException InvalidSizeValue(int value)
1407         {
1408             return Argument(System.Data.Entity.Strings.ADP_InvalidSizeValue(value.ToString(CultureInfo.InvariantCulture)));
1409         }
1410
1411         static internal ArgumentException ConnectionStringSyntax(int index)
1412         {
1413             return Argument(System.Data.Entity.Strings.ADP_ConnectionStringSyntax(index));
1414         }
1415
1416         internal static InvalidOperationException DataRecordMustBeEntity() {
1417             return InvalidOperation(System.Data.Entity.Strings.EntityKey_DataRecordMustBeEntity);
1418         }
1419         internal static ArgumentException EntitySetDoesNotMatch(string argument, string entitySetName) {
1420             return Argument(System.Data.Entity.Strings.EntityKey_EntitySetDoesNotMatch(entitySetName), argument);
1421         }
1422         internal static InvalidOperationException EntityTypesDoNotMatch(string recordType, string entitySetType) {
1423             return InvalidOperation(System.Data.Entity.Strings.EntityKey_EntityTypesDoNotMatch(recordType, entitySetType));
1424         }
1425         internal static ArgumentException IncorrectNumberOfKeyValuePairs(string argument, string typeName, int expectedNumFields, int actualNumFields) {
1426             return Argument(System.Data.Entity.Strings.EntityKey_IncorrectNumberOfKeyValuePairs(typeName, expectedNumFields, actualNumFields), argument);
1427         }
1428         internal static InvalidOperationException IncorrectNumberOfKeyValuePairsInvalidOperation(string typeName, int expectedNumFields, int actualNumFields)
1429         {
1430             return InvalidOperation(System.Data.Entity.Strings.EntityKey_IncorrectNumberOfKeyValuePairs(typeName, expectedNumFields, actualNumFields));
1431         }
1432         internal static ArgumentException IncorrectValueType(string argument, string keyField, string expectedTypeName, string actualTypeName) {
1433             return Argument(System.Data.Entity.Strings.EntityKey_IncorrectValueType(keyField, expectedTypeName, actualTypeName), argument);
1434         }
1435         internal static InvalidOperationException IncorrectValueTypeInvalidOperation(string keyField, string expectedTypeName, string actualTypeName) {
1436             return InvalidOperation(System.Data.Entity.Strings.EntityKey_IncorrectValueType(keyField, expectedTypeName, actualTypeName));
1437         }
1438         internal static ArgumentException NoCorrespondingOSpaceTypeForEnumKeyField(string argument, string keyField, string cspaceTypeName) {
1439             return Argument(System.Data.Entity.Strings.EntityKey_NoCorrespondingOSpaceTypeForEnumKeyMember(keyField, cspaceTypeName), argument);
1440         }
1441         internal static InvalidOperationException NoCorrespondingOSpaceTypeForEnumKeyFieldInvalidOperation(string keyField, string cspaceTypeName) {
1442             return InvalidOperation(System.Data.Entity.Strings.EntityKey_NoCorrespondingOSpaceTypeForEnumKeyMember(keyField, cspaceTypeName));
1443         }
1444         internal static ArgumentException MissingKeyValue(string argument, string keyField, string typeName) {
1445             return MissingKeyValue(argument, keyField, typeName, null);
1446         }
1447         internal static ArgumentException MissingKeyValue(string argument, string keyField, string typeName, Exception inner) {
1448             return Argument(System.Data.Entity.Strings.EntityKey_MissingKeyValue(keyField, typeName), argument);
1449         }
1450         internal static InvalidOperationException NullKeyValue(string keyField, string typeName)
1451         {
1452             return InvalidOperation(System.Data.Entity.Strings.EntityKey_NullKeyValue(keyField, typeName));
1453         }
1454         internal static InvalidOperationException MissingKeyValueInvalidOperation(string keyField, string typeName)
1455         {
1456             return InvalidOperation(System.Data.Entity.Strings.EntityKey_MissingKeyValue(keyField, typeName));
1457         }
1458         internal static ArgumentException NoNullsAllowedInKeyValuePairs(string argument) {
1459             return Argument(System.Data.Entity.Strings.EntityKey_NoNullsAllowedInKeyValuePairs, argument);
1460         }
1461         internal static ArgumentException EntityKeyMustHaveValues(string argument) {
1462             return Argument(System.Data.Entity.Strings.EntityKey_EntityKeyMustHaveValues, argument);
1463         }
1464         internal static ArgumentException InvalidQualifiedEntitySetName() {
1465             return Argument(System.Data.Entity.Strings.EntityKey_InvalidQualifiedEntitySetName, "qualifiedEntitySetName");
1466         }
1467         internal static ArgumentException EntityKeyInvalidName(string invalidName) {
1468             return Argument(System.Data.Entity.Strings.EntityKey_InvalidName(invalidName));
1469         }
1470         internal static InvalidOperationException MissingQualifiedEntitySetName() {
1471             return InvalidOperation(System.Data.Entity.Strings.EntityKey_MissingEntitySetName);
1472         }
1473         internal static InvalidOperationException CannotChangeEntityKey() {
1474             return InvalidOperation(System.Data.Entity.Strings.EntityKey_CannotChangeKey);
1475         }
1476
1477         internal static InvalidOperationException UnexpectedNullEntityKey()
1478         {
1479             return new InvalidOperationException(System.Data.Entity.Strings.EntityKey_UnexpectedNull);
1480         }
1481         internal static InvalidOperationException EntityKeyDoesntMatchKeySetOnEntity(object entity)
1482         {
1483             return new InvalidOperationException(System.Data.Entity.Strings.EntityKey_DoesntMatchKeyOnEntity(entity.GetType().FullName));
1484         }
1485         internal static void CheckEntityKeyNull(EntityKey entityKey)
1486         {
1487             if ((object)entityKey == null)
1488             {
1489                 throw EntityUtil.UnexpectedNullEntityKey();
1490             }
1491         }
1492         internal static void CheckEntityKeysMatch(IEntityWrapper wrappedEntity, EntityKey key)
1493         {
1494             if (wrappedEntity.EntityKey != key)
1495             {
1496                 throw EntityUtil.EntityKeyDoesntMatchKeySetOnEntity(wrappedEntity.Entity);
1497             }
1498         }
1499         internal static InvalidOperationException UnexpectedNullRelationshipManager()
1500         {
1501             return new InvalidOperationException(System.Data.Entity.Strings.RelationshipManager_UnexpectedNull);
1502         }
1503         internal static InvalidOperationException InvalidRelationshipManagerOwner()
1504         {
1505             return EntityUtil.InvalidOperation(System.Data.Entity.Strings.RelationshipManager_InvalidRelationshipManagerOwner);
1506         }
1507
1508         internal static void ValidateEntitySetInKey(EntityKey key, EntitySet entitySet)
1509         {
1510             ValidateEntitySetInKey(key, entitySet, null);
1511         }
1512         internal static void ValidateEntitySetInKey(EntityKey key, EntitySet entitySet, string argument)
1513         {
1514             Debug.Assert(null != (object)key, "Null entity key");
1515             Debug.Assert(null != entitySet, "Null entity set");
1516             Debug.Assert(null != entitySet.EntityContainer, "Null entity container in the entity set");
1517
1518             string containerName1 = key.EntityContainerName;
1519             string setName1 = key.EntitySetName;
1520             string containerName2 = entitySet.EntityContainer.Name;
1521             string setName2 = entitySet.Name;
1522
1523             if (!StringComparer.Ordinal.Equals(containerName1, containerName2) ||
1524                 !StringComparer.Ordinal.Equals(setName1, setName2))
1525             {
1526                 if (String.IsNullOrEmpty(argument))
1527                 {
1528                     throw EntityUtil.InvalidEntitySetInKey(
1529                         containerName1, setName1,
1530                         containerName2, setName2);
1531                 }
1532                 else
1533                 {
1534                     throw EntityUtil.InvalidEntitySetInKeyFromName(
1535                         containerName1, setName1,
1536                         containerName2, setName2, argument);
1537                 }
1538             }
1539         }
1540
1541
1542
1543         // IDataParameter.Direction
1544         static internal ArgumentOutOfRangeException InvalidMergeOption(MergeOption value) {
1545 #if DEBUG
1546             switch(value) {
1547             case MergeOption.NoTracking:
1548             case MergeOption.OverwriteChanges:
1549             case MergeOption.PreserveChanges:
1550             case MergeOption.AppendOnly:
1551                 Debug.Assert(false, "valid MergeOption " + value.ToString());
1552                 break;
1553             }
1554 #endif
1555             return InvalidEnumerationValue(typeof(MergeOption), (int) value);
1556         }
1557
1558         static internal ArgumentOutOfRangeException InvalidRefreshMode(RefreshMode value) {
1559 #if DEBUG
1560             switch(value) {
1561             case RefreshMode.ClientWins:
1562             case RefreshMode.StoreWins:
1563                 Debug.Assert(false, "valid RefreshMode " + value.ToString());
1564                 break;
1565             }
1566 #endif
1567             return InvalidEnumerationValue(typeof(RefreshMode), (int) value);
1568         }
1569
1570         //
1571         // : IDataParameter
1572         //
1573         static internal ArgumentException InvalidDataType(TypeCode typecode) {
1574             return Argument(System.Data.Entity.Strings.ADP_InvalidDataType(typecode.ToString()));
1575         }
1576
1577         static internal ArgumentException UnknownDataTypeCode(Type dataType, TypeCode typeCode) {
1578             return Argument(System.Data.Entity.Strings.ADP_UnknownDataTypeCode(((int) typeCode).ToString(CultureInfo.InvariantCulture), dataType.FullName));
1579         }
1580
1581         static internal ArgumentOutOfRangeException InvalidParameterDirection(ParameterDirection value)
1582         {
1583 #if DEBUG
1584             switch (value)
1585             {
1586                 case ParameterDirection.Input:
1587                 case ParameterDirection.Output:
1588                 case ParameterDirection.InputOutput:
1589                 case ParameterDirection.ReturnValue:
1590                     Debug.Assert(false, "valid ParameterDirection " + value.ToString());
1591                     break;
1592             }
1593 #endif
1594             return InvalidEnumerationValue(typeof(ParameterDirection), (int)value);
1595         }
1596         static internal ArgumentOutOfRangeException InvalidDataRowVersion(DataRowVersion value)
1597         {
1598 #if DEBUG
1599             switch (value)
1600             {
1601                 case DataRowVersion.Default:
1602                 case DataRowVersion.Current:
1603                 case DataRowVersion.Original:
1604                 case DataRowVersion.Proposed:
1605                     Debug.Assert(false, "valid DataRowVersion " + value.ToString());
1606                     break;
1607             }
1608 #endif
1609
1610             return InvalidEnumerationValue(typeof(DataRowVersion), (int)value);
1611         }
1612         //
1613         // UpdateException
1614         //
1615         static private IEnumerable<ObjectStateEntry> ProcessStateEntries(IEnumerable<IEntityStateEntry> stateEntries)
1616         {
1617             return stateEntries
1618             // In a future release, IEntityStateEntry will be public so we will be able to throw exceptions 
1619             // with this more general type. For now we cast to ObjectStateEntry (the only implementation
1620             // of the internal interface).
1621                 .Cast<ObjectStateEntry>()
1622             // Return distinct entries (no need to report an entry multiple times even if it contributes
1623             // to the exception in multiple ways)
1624                 .Distinct();
1625         }
1626         static internal void ValidateNecessaryModificationFunctionMapping(
1627                 StorageModificationFunctionMapping mapping, string currentState,
1628                 IEntityStateEntry stateEntry, string type, string typeName)
1629         {
1630             if (null == mapping)
1631             {
1632                 throw EntityUtil.Update(Strings.Update_MissingFunctionMapping(currentState, type, typeName),
1633                 null,
1634                 new List<IEntityStateEntry>() { stateEntry });
1635             }
1636         }
1637         static internal UpdateException Update(string message, Exception innerException, params IEntityStateEntry[] stateEntries) {
1638             return Update(message, innerException, (IEnumerable<IEntityStateEntry>)stateEntries);
1639         }
1640         static internal UpdateException Update(string message, Exception innerException, IEnumerable<IEntityStateEntry> stateEntries)
1641         {
1642             return new UpdateException(message, innerException, ProcessStateEntries(stateEntries));
1643         }
1644         static internal OptimisticConcurrencyException UpdateConcurrency(long rowsAffected, Exception innerException, IEnumerable<IEntityStateEntry> stateEntries)
1645         {
1646             string message = System.Data.Entity.Strings.Update_ConcurrencyError(rowsAffected);
1647             return new OptimisticConcurrencyException(message, innerException, ProcessStateEntries(stateEntries));
1648         }
1649         static internal UpdateException UpdateRelationshipCardinalityConstraintViolation(string relationshipSetName,
1650             int minimumCount, int? maximumCount, string entitySetName, int actualCount, string otherEndPluralName, IEntityStateEntry stateEntry) {
1651             string minimumCountString = ConvertCardinalityToString(minimumCount);
1652             string maximumCountString = ConvertCardinalityToString(maximumCount);
1653             string actualCountString = ConvertCardinalityToString(actualCount);
1654             if (minimumCount == 1 && (minimumCountString == maximumCountString))
1655             {
1656                 // Just one acceptable value and itis value is 1
1657                 return Update(System.Data.Entity.Strings.Update_RelationshipCardinalityConstraintViolationSingleValue(
1658                     entitySetName, relationshipSetName, actualCountString, otherEndPluralName,
1659                     minimumCountString), null, stateEntry);
1660             }
1661             else
1662             {
1663                 // Range of acceptable values
1664                 return Update(System.Data.Entity.Strings.Update_RelationshipCardinalityConstraintViolation(
1665                     entitySetName, relationshipSetName, actualCountString, otherEndPluralName,
1666                     minimumCountString, maximumCountString), null, stateEntry);
1667             }
1668         }
1669         static internal UpdateException UpdateEntityMissingConstraintViolation(string relationshipSetName, string endName, IEntityStateEntry stateEntry) {
1670             string message = System.Data.Entity.Strings.Update_MissingRequiredEntity(relationshipSetName, stateEntry.State, endName);
1671             return Update(message, null, stateEntry);
1672         }
1673         static private string ConvertCardinalityToString(int? cardinality) {
1674             string result;
1675             if (!cardinality.HasValue) { // null indicates * (unlimited)
1676                 result = "*";
1677             }
1678             else {
1679                 result = cardinality.Value.ToString(CultureInfo.CurrentCulture);
1680             }
1681             return result;
1682         }
1683         static internal UpdateException UpdateMissingEntity(string relationshipSetName, string entitySetName) {
1684             return Update(System.Data.Entity.Strings.Update_MissingEntity(relationshipSetName, entitySetName), null);
1685         }
1686
1687         static internal ArgumentException CollectionParameterElementIsNull(string parameterName) {
1688             return Argument(System.Data.Entity.Strings.ADP_CollectionParameterElementIsNull(parameterName));
1689         }
1690         static internal ArgumentException CollectionParameterElementIsNullOrEmpty(string parameterName) {
1691             return Argument(System.Data.Entity.Strings.ADP_CollectionParameterElementIsNullOrEmpty(parameterName));
1692         }
1693
1694         static internal InvalidOperationException FunctionHasNoDefinition(EdmFunction function)
1695         {
1696             return InvalidOperation(System.Data.Entity.Strings.Cqt_UDF_FunctionHasNoDefinition(function.Identity));
1697         }
1698
1699         static internal InvalidOperationException FunctionDefinitionResultTypeMismatch(EdmFunction function, TypeUsage generatedDefinitionResultType)
1700         {
1701             return InvalidOperation(System.Data.Entity.Strings.Cqt_UDF_FunctionDefinitionResultTypeMismatch(
1702                 TypeHelpers.GetFullName(function.ReturnParameter.TypeUsage),
1703                 function.FullName,
1704                 TypeHelpers.GetFullName(generatedDefinitionResultType)));
1705         }
1706
1707         static internal Exception EntityParameterCollectionInvalidIndex(int index, int count)
1708         {
1709             return new IndexOutOfRangeException(System.Data.Entity.Strings.EntityParameterCollectionInvalidIndex(index.ToString(CultureInfo.InvariantCulture), count.ToString(CultureInfo.InvariantCulture)));
1710         }
1711         static internal Exception EntityParameterCollectionInvalidParameterName(string parameterName)
1712         {
1713             return new IndexOutOfRangeException(System.Data.Entity.Strings.EntityParameterCollectionInvalidParameterName(parameterName));
1714         }
1715         static internal Exception EntityParameterNull(string parameter)
1716         {
1717             return new ArgumentNullException(parameter, System.Data.Entity.Strings.EntityParameterNull);
1718         }
1719         static internal Exception InvalidEntityParameterType(object invalidValue)
1720         {
1721             return new InvalidCastException(System.Data.Entity.Strings.InvalidEntityParameterType(invalidValue.GetType().Name));
1722         }
1723         static internal ArgumentException EntityParameterCollectionRemoveInvalidObject()
1724         {
1725             return new ArgumentException(System.Data.Entity.Strings.EntityParameterCollectionRemoveInvalidObject); 
1726         }
1727         static internal ArgumentException EntityParameterContainedByAnotherCollection()
1728         {
1729             return new ArgumentException(System.Data.Entity.Strings.EntityParameterContainedByAnotherCollection);
1730         }
1731         ////////////////////////////////////////////////////////////////////////
1732         ////////////////////////////////////////////////////////////////////////
1733         ////////////////////////////////////////////////////////////////////////
1734         //
1735         // Helper Functions
1736         //
1737         internal static void ThrowArgumentNullException(string parameterName)
1738         {
1739             throw ArgumentNull(parameterName);
1740         }
1741         internal static void ThrowArgumentOutOfRangeException(string parameterName)
1742         {
1743             throw ArgumentOutOfRange(parameterName);
1744         }
1745         internal static T CheckArgumentOutOfRange<T>(T[] values, int index, string parameterName)
1746         {
1747             Debug.Assert(null != values, "null values"); // use a different method if values can be null
1748             if (unchecked((uint)values.Length <= (uint)index))
1749             {
1750                 ThrowArgumentOutOfRangeException(parameterName);
1751             }
1752             return values[index];
1753         }
1754
1755         static internal T CheckArgumentNull<T>(T value, string parameterName) where T : class
1756         {
1757             if (null == value)
1758             {
1759                 ThrowArgumentNullException(parameterName);
1760             }
1761             return value;
1762         }
1763
1764         static internal IEnumerable<T> CheckArgumentContainsNull<T>(ref IEnumerable<T> enumerableArgument, string argumentName) where T : class
1765         {
1766             GetCheapestSafeEnumerableAsCollection(ref enumerableArgument);
1767             foreach (T item in enumerableArgument)
1768             {
1769                 if(item == null)
1770                 {
1771                     throw EntityUtil.Argument(Strings.CheckArgumentContainsNullFailed(argumentName));
1772                 }
1773             }
1774             return enumerableArgument;
1775         }
1776
1777         static internal IEnumerable<T> CheckArgumentEmpty<T>(ref IEnumerable<T> enumerableArgument, Func<string, string> errorMessage, string argumentName)
1778         {
1779             int count;
1780             GetCheapestSafeCountOfEnumerable(ref enumerableArgument, out count);
1781             if (count <= 0)
1782             {
1783                 throw EntityUtil.Argument(errorMessage(argumentName));
1784             }
1785             return enumerableArgument;
1786         }
1787
1788         private static void GetCheapestSafeCountOfEnumerable<T>(ref IEnumerable<T> enumerable, out int count)
1789         {
1790             ICollection<T> collection = GetCheapestSafeEnumerableAsCollection(ref enumerable);
1791             count = collection.Count;
1792         }
1793
1794         private static ICollection<T> GetCheapestSafeEnumerableAsCollection<T>(ref IEnumerable<T> enumerable)
1795         {
1796             ICollection<T> collection = enumerable as ICollection<T>;
1797             if (collection != null)
1798             {
1799                 // cheap way
1800                 return collection;
1801             }
1802
1803             // expensive way, but we don't know if the enumeration is rewindable so...
1804             enumerable = new List<T>(enumerable);
1805             return enumerable as ICollection<T>;
1806         }
1807
1808         static internal T GenericCheckArgumentNull<T>(T value, string parameterName) where T: class
1809         {
1810             return CheckArgumentNull(value, parameterName);
1811         }
1812
1813         // EntityConnectionStringBuilder
1814         static internal ArgumentException KeywordNotSupported(string keyword)
1815         {
1816             return Argument(System.Data.Entity.Strings.EntityClient_KeywordNotSupported(keyword));
1817         }
1818
1819         static internal ArgumentException ADP_KeywordNotSupported(string keyword)
1820         {
1821             return Argument(System.Data.Entity.Strings.ADP_KeywordNotSupported(keyword));
1822         }
1823
1824         // Invalid Enumeration
1825
1826         static internal ArgumentOutOfRangeException InvalidEnumerationValue(Type type, int value) {
1827             return EntityUtil.ArgumentOutOfRange(System.Data.Entity.Strings.ADP_InvalidEnumerationValue(type.Name, value.ToString(System.Globalization.CultureInfo.InvariantCulture)), type.Name);
1828         }
1829
1830         /// <summary>
1831         /// Given a provider factory, this returns the provider invariant name for the provider. 
1832         /// </summary>
1833         [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
1834         internal static bool TryGetProviderInvariantName(DbProviderFactory providerFactory, out string invariantName)
1835         {
1836             Debug.Assert(providerFactory != null);
1837
1838             var connectionProviderFactoryType = providerFactory.GetType();
1839             var connectionProviderFactoryAssemblyName = new AssemblyName(
1840                 connectionProviderFactoryType.Assembly.FullName);
1841
1842             foreach (DataRow row in DbProviderFactories.GetFactoryClasses().Rows)
1843             {
1844                 var assemblyQualifiedTypeName = (string)row[AssemblyQualifiedNameIndex];
1845
1846                 AssemblyName rowProviderFactoryAssemblyName = null;
1847
1848                 // parse the provider factory assembly qualified type name
1849                 Type.GetType(
1850                     assemblyQualifiedTypeName,
1851                     a =>
1852                     {
1853                         rowProviderFactoryAssemblyName = a;
1854
1855                         return null;
1856                     },
1857                     (_, __, ___) => null);
1858
1859                 if (rowProviderFactoryAssemblyName != null)
1860                 {
1861                     if (string.Equals(
1862                         connectionProviderFactoryAssemblyName.Name,
1863                         rowProviderFactoryAssemblyName.Name,
1864                         StringComparison.OrdinalIgnoreCase))
1865                     {
1866                         try
1867                         {
1868                             var foundFactory = DbProviderFactories.GetFactory(row);
1869
1870                             if (foundFactory.GetType().Equals(connectionProviderFactoryType))
1871                             {
1872                                 invariantName = (string)row[InvariantNameIndex];
1873                                 return true;
1874                             }
1875                         }
1876                         catch (Exception ex)
1877                         {
1878                             Debug.Fail("GetFactory failed with: " + ex);
1879                             // Ignore bad providers.
1880                         }
1881                     }
1882                 }
1883             }
1884             invariantName = null;
1885             return false;
1886         }
1887
1888         static internal bool AssemblyNamesMatch(string infoRowProviderAssemblyName, AssemblyName targetAssemblyName)
1889         {
1890             if (string.IsNullOrWhiteSpace(infoRowProviderAssemblyName))
1891             {
1892                 return false;
1893             }
1894
1895             AssemblyName assemblyName = null;
1896             try
1897             {
1898                 assemblyName = new AssemblyName(infoRowProviderAssemblyName);
1899             }
1900             catch (Exception e)
1901             {
1902                 // Ignore broken provider entries
1903                 if (!IsCatchableExceptionType(e))
1904                 {
1905                     throw;
1906                 }
1907                 return false;
1908             }
1909
1910             Debug.Assert(assemblyName != null, "assemblyName should not be null at this point");
1911
1912             // Match the provider assembly details
1913             if (! string.Equals(targetAssemblyName.Name, assemblyName.Name, StringComparison.OrdinalIgnoreCase))
1914             {
1915                 return false;
1916             }
1917
1918             if (targetAssemblyName.Version == null || assemblyName.Version == null)
1919             {
1920                 return false;
1921             }
1922
1923             if ((targetAssemblyName.Version.Major != assemblyName.Version.Major) || 
1924                 (targetAssemblyName.Version.Minor != assemblyName.Version.Minor))
1925             {
1926                 return false;
1927             }
1928
1929             var targetPublicKeyToken = targetAssemblyName.GetPublicKeyToken();        
1930             return (targetPublicKeyToken != null)
1931                 && targetPublicKeyToken.SequenceEqual(assemblyName.GetPublicKeyToken());
1932         }
1933
1934         // Invalid string argument
1935         static internal void CheckStringArgument(string value, string parameterName)
1936         {
1937             // Throw ArgumentNullException when string is null
1938             CheckArgumentNull(value, parameterName);
1939
1940             // Throw ArgumentException when string is empty
1941             if (value.Length == 0)
1942             {
1943                 throw InvalidStringArgument(parameterName);
1944             }
1945         }
1946
1947         // only StackOverflowException & ThreadAbortException are sealed classes
1948         static private readonly Type StackOverflowType   = typeof(System.StackOverflowException);
1949         static private readonly Type OutOfMemoryType     = typeof(System.OutOfMemoryException);
1950         static private readonly Type ThreadAbortType     = typeof(System.Threading.ThreadAbortException);
1951         static private readonly Type NullReferenceType   = typeof(System.NullReferenceException);
1952         static private readonly Type AccessViolationType = typeof(System.AccessViolationException);
1953         static private readonly Type SecurityType        = typeof(System.Security.SecurityException);
1954         static private readonly Type CommandExecutionType = typeof(EntityCommandExecutionException);
1955         static private readonly Type CommandCompilationType = typeof(EntityCommandCompilationException);
1956         static private readonly Type QueryType = typeof(EntitySqlException);
1957
1958         static internal bool IsCatchableExceptionType (Exception e) {
1959             // a 'catchable' exception is defined by what it is not.
1960             Debug.Assert(e != null, "Unexpected null exception!");
1961             Type type = e.GetType();
1962
1963             return ( (type != StackOverflowType) &&
1964                      (type != OutOfMemoryType)   &&
1965                      (type != ThreadAbortType)   &&
1966                      (type != NullReferenceType) &&
1967                      (type != AccessViolationType) &&
1968                      !SecurityType.IsAssignableFrom(type));
1969         }
1970
1971         static internal bool IsCatchableEntityExceptionType(Exception e)
1972         {
1973             Debug.Assert(e != null, "Unexpected null exception!");
1974             Type type = e.GetType();
1975
1976             return IsCatchableExceptionType(e) &&
1977                 type != CommandExecutionType &&
1978                 type != CommandCompilationType &&
1979                 type != QueryType;
1980         }
1981
1982         static internal bool IsNull(object value) {
1983             if ((null == value) || (DBNull.Value == value)) {
1984                 return true;
1985             }
1986             INullable nullable = (value as INullable);
1987             return ((null != nullable) && nullable.IsNull);
1988         }
1989
1990         /// <summary>
1991         /// Utility method to raise internal error when a throttling constraint is violated during
1992         /// Boolean expression analysis. An internal exception is thrown including the given message
1993         /// if the given condition is false. This allows us to give up on an unexpectedly difficult
1994         /// computation rather than risk hanging the user's machine.
1995         /// </summary>
1996         static internal void BoolExprAssert(bool condition, string message)
1997         {
1998             if (!condition)
1999             {
2000                 throw InternalError(InternalErrorCode.BoolExprAssert, 0, message);
2001             }
2002         }
2003
2004         static internal PropertyInfo GetTopProperty(Type t, string propertyName)
2005         {
2006             return GetTopProperty(ref t, propertyName);
2007         }
2008
2009         /// <summary>
2010         /// Returns the PropertyInfo and Type where a given property is defined
2011         /// This is done by traversing the type hierarchy to find the type match.
2012         /// </summary>
2013         /// <param name="t"></param>
2014         /// <param name="propertyName"></param>
2015         /// <returns></returns>
2016         static internal PropertyInfo GetTopProperty(ref Type t, string propertyName)
2017         {
2018             PropertyInfo propertyInfo = null;
2019             while (propertyInfo == null && t != null)
2020             {
2021                 propertyInfo = t.GetProperty(propertyName, BindingFlags.Instance |
2022                                                            BindingFlags.Public |
2023                                                            BindingFlags.NonPublic |
2024                                                            BindingFlags.DeclaredOnly);
2025                 t = t.BaseType;
2026             }
2027             t = propertyInfo.DeclaringType;
2028             return propertyInfo;
2029         }
2030
2031         static internal int SrcCompare(string strA, string strB)
2032         { 
2033             return ((strA == strB) ? 0 : 1);
2034         }
2035         static internal int DstCompare(string strA, string strB)
2036         {
2037             return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, EntityUtil.StringCompareOptions);
2038         }
2039
2040         internal static Dictionary<string,string> COMPILER_VERSION = new Dictionary<string, string>() { { "CompilerVersion", "V3.5" } }; //v3.5 required for compiling model files with partial methods.
2041
2042         [FileIOPermission(SecurityAction.Assert, AllFiles = FileIOPermissionAccess.PathDiscovery)]
2043         [Security.SecuritySafeCritical]
2044         [ResourceExposure(ResourceScope.Machine)]
2045         [ResourceConsumption(ResourceScope.Machine)]
2046         static internal string GetFullPath(string filename)
2047         { // MDAC 77686
2048             return Path.GetFullPath(filename);
2049         }
2050 #if false
2051         public static T FieldCast<T>(object value) {
2052             try {
2053                 // will result in an InvalidCastException if !(value is T)
2054                 // this pattern also supports handling System.Data.SqlTypes
2055                 return (T)((DBNull.Value == value) ? null : value);
2056             }
2057             catch(NullReferenceException) {
2058                 // (value == null) and (T is struct) and (T is not Nullable<>), convert to InvalidCastException
2059                 return (T)(object)System.DBNull.Value;
2060             }
2061         }
2062 #endif    
2063     
2064         public static Type[] GetTypesSpecial(Assembly assembly)
2065         {
2066             return ReferenceEquals(assembly, typeof(ObjectContext).Assembly)
2067                        ? new Type[0]
2068                        : assembly.GetTypes();
2069         }
2070
2071         /// <summary>
2072         /// This method uses the .net Fx target framework moniker (introduced in .net 4.0 Multitargeting feature)
2073         /// to provide a 'quirks' mode that serves as a compatibility flag for features that can be considered
2074         /// breaking changes from 4.0 to 4.5 which is a in-place upgrade to 4.0.  For details see DevDiv2 bug#488375.
2075         /// </summary>
2076         static bool? useFx40CompatMode;
2077         static public bool UseFx40CompatMode
2078         {
2079             get
2080             {
2081                 if (!useFx40CompatMode.HasValue)
2082                 {
2083                     string fxname = AppDomain.CurrentDomain.SetupInformation.TargetFrameworkName;
2084
2085                     if (string.IsNullOrWhiteSpace(fxname))
2086                     {
2087                         Assembly entryAssembly = Assembly.GetEntryAssembly(); // entry assembly can be unmanaged.
2088
2089                         if (entryAssembly != null)
2090                         {
2091                             TargetFrameworkAttribute fxAttrib = entryAssembly.GetCustomAttribute<TargetFrameworkAttribute>();
2092                             if (fxAttrib != null)
2093                             {
2094                                 fxname = fxAttrib.FrameworkName;
2095                             }
2096                         }
2097                     }
2098
2099                     if (!string.IsNullOrWhiteSpace(fxname))
2100                     {
2101                         try
2102                         {
2103                             FrameworkName compiledFxName = new FrameworkName(fxname);
2104                             Version fxv45 = new Version(4, 5);
2105
2106                             useFx40CompatMode = compiledFxName.Version < fxv45;
2107                         }
2108                         catch (System.ArgumentException)
2109                         {
2110                         }
2111                     }
2112
2113                     if (!useFx40CompatMode.HasValue)
2114                     {
2115                         useFx40CompatMode = true;
2116                     }
2117                 }
2118
2119                 return useFx40CompatMode.Value;
2120             }
2121         }
2122
2123     }
2124 }