1 //------------------------------------------------------------------------------
2 // <copyright file="EntityUtil.cs" company="Microsoft">
3 // Copyright (c) Microsoft Corporation. All rights reserved.
5 // <owner current="true" primary="true">Microsoft</owner>
6 //------------------------------------------------------------------------------
8 namespace System.Data {
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;
25 using System.Reflection;
26 using System.Runtime.Versioning;
27 using System.Security.Permissions;
30 internal static class EntityUtil {
32 internal const int AssemblyQualifiedNameIndex = 3;
33 internal const int InvariantNameIndex = 2;
35 internal const string Parameter = "Parameter";
37 internal const CompareOptions StringCompareOptions = CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase;
39 internal static bool? ThreeValuedNot(bool? operand) {
40 // three-valued logic 'not' (T = true, F = false, U = unknown)
44 return operand.HasValue ? !operand.Value : (bool?)null;
46 internal static bool? ThreeValuedAnd(bool? left, bool? right) {
47 // three-valued logic 'and' (T = true, F = false, U = unknown)
59 if (left.HasValue && right.HasValue) {
60 result = left.Value && right.Value;
62 else if (!left.HasValue && !right.HasValue) {
63 result = null; // unknown
65 else if (left.HasValue) {
67 (bool?)null :// unknown
71 result = right.Value ?
78 internal static bool? ThreeValuedOr(bool? left, bool? right) {
79 // three-valued logic 'or' (T = true, F = false, U = unknown)
91 if (left.HasValue && right.HasValue) {
92 result = left.Value || right.Value;
94 else if (!left.HasValue && !right.HasValue) {
95 result = null; // unknown
97 else if (left.HasValue) {
100 (bool?)null; // unknown
103 result = right.Value ?
105 (bool?)null; // unknown
111 /// Zips two enumerables together (e.g., given {1, 3, 5} and {2, 4, 6} returns {{1, 2}, {3, 4}, {5, 6}})
113 internal static IEnumerable<KeyValuePair<T1, T2>> Zip<T1, T2>(this IEnumerable<T1> first, IEnumerable<T2> second)
115 if (null == first || null == second) { yield break; }
116 using (IEnumerator<T1> firstEnumerator = first.GetEnumerator())
117 using (IEnumerator<T2> secondEnumerator = second.GetEnumerator())
119 while (firstEnumerator.MoveNext() && secondEnumerator.MoveNext())
121 yield return new KeyValuePair<T1, T2>(firstEnumerator.Current, secondEnumerator.Current);
127 /// Returns true if the type implements ICollection<>
129 internal static bool IsAnICollection(Type type)
131 return typeof(ICollection<>).IsAssignableFrom(type.GetGenericTypeDefinition()) ||
132 type.GetInterface(typeof(ICollection<>).FullName) != null;
137 /// Given a type that represents a collection, determine if the type implements ICollection<>, and if
138 /// so return the element type of the collection. Currently, if the collection implements ICollection<>
139 /// multiple times with different types, then we will return false since this is not supported.
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<> false otherwise</returns>
144 internal static bool TryGetICollectionElementType(Type collectionType, out Type elementType)
147 // We have to check if the type actually is the interface, or if it implements the interface:
150 Type collectionInterface =
151 (collectionType.IsGenericType && typeof(ICollection<>).IsAssignableFrom(collectionType.GetGenericTypeDefinition())) ?
153 collectionType.GetInterface(typeof(ICollection<>).FullName);
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)
158 elementType = collectionInterface.GetGenericArguments()[0];
163 catch (AmbiguousMatchException)
165 // Thrown if collection type implements ICollection<> more than once
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.
174 internal static Type GetCollectionElementType(Type propertyType)
177 if (!EntityUtil.TryGetICollectionElementType(propertyType, out elementType))
179 throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.PocoEntityWrapper_UnexpectedTypeForNavigationProperty(
180 propertyType.FullName,
181 typeof(ICollection<>)));
187 /// This is used when we need to determine a concrete collection type given some type that may be
188 /// abstract or an interface.
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.
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)
201 const BindingFlags constructorBinding = BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance;
203 var elementType = EntityUtil.GetCollectionElementType(requestedType);
205 if (requestedType.IsArray)
207 throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectQuery_UnableToMaterializeArray(
208 requestedType, typeof(List<>).MakeGenericType(elementType)));
211 if (!requestedType.IsAbstract &&
212 requestedType.GetConstructor(constructorBinding, null, System.Type.EmptyTypes, null) != null)
214 return requestedType;
217 var hashSetOfT = typeof(HashSet<>).MakeGenericType(elementType);
218 if (requestedType.IsAssignableFrom(hashSetOfT))
223 var listOfT = typeof(List<>).MakeGenericType(elementType);
224 if (requestedType.IsAssignableFrom(listOfT))
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.
239 internal static Type GetEntityIdentityType(Type entityType)
241 return EntityProxyFactory.IsProxyType(entityType) ? entityType.BaseType : entityType;
245 /// Provides a standard helper method for quoting identifiers
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)
251 Debug.Assert(identifier != null, "identifier should not be null");
252 return "[" + identifier.Replace("]", "]]") + "]";
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.
261 static internal ArgumentException Argument(string error) {
262 return new ArgumentException(error);
264 static internal ArgumentException Argument(string error, Exception inner) {
265 return new ArgumentException(error, inner);
267 static internal ArgumentException Argument(string error, string parameter) {
268 return new ArgumentException(error, parameter);
270 static internal ArgumentException Argument(string error, string parameter, Exception inner) {
271 return new ArgumentException(error, parameter, inner);
273 static internal ArgumentNullException ArgumentNull(string parameter) {
274 return new ArgumentNullException(parameter);
276 static internal ArgumentOutOfRangeException ArgumentOutOfRange(string parameterName) {
277 return new ArgumentOutOfRangeException(parameterName);
279 static internal ArgumentOutOfRangeException ArgumentOutOfRange(string message, string parameterName) {
280 return new ArgumentOutOfRangeException(parameterName, message);
282 static internal EntityCommandExecutionException CommandExecution(string message) {
283 return new EntityCommandExecutionException(message);
285 static internal EntityCommandExecutionException CommandExecution(string message, Exception innerException) {
286 return new EntityCommandExecutionException(message, innerException);
288 static internal EntityCommandCompilationException CommandCompilation(string message, Exception innerException) {
289 return new EntityCommandCompilationException(message, innerException);
291 static internal PropertyConstraintException PropertyConstraint(string message, string propertyName)
293 return new PropertyConstraintException(message, propertyName);
295 static internal ConstraintException Constraint(string message)
297 return new ConstraintException(message);
299 static internal IndexOutOfRangeException IndexOutOfRange(string error)
301 return new IndexOutOfRangeException(error);
303 static internal InvalidOperationException InvalidOperation(string error) {
304 return new InvalidOperationException(error);
306 static internal InvalidOperationException InvalidOperation(string error, Exception inner) {
307 return new InvalidOperationException(error, inner);
309 static internal ArgumentException InvalidStringArgument(string parameterName) {
310 return Argument(System.Data.Entity.Strings.InvalidStringArgument(parameterName), parameterName);
312 static internal MappingException Mapping(string message)
314 return new MappingException(message);
316 static internal MetadataException Metadata(string message, Exception inner)
318 return new MetadataException(message, inner);
320 static internal MetadataException Metadata(string message)
322 return new MetadataException(message);
324 static internal NotSupportedException NotSupported()
326 return new NotSupportedException();
328 static internal NotSupportedException NotSupported(string error) {
329 return new NotSupportedException(error);
331 static internal ObjectDisposedException ObjectDisposed(string error) {
332 return new ObjectDisposedException(null, error);
334 static internal ObjectNotFoundException ObjectNotFound(string error) {
335 return new ObjectNotFoundException(error);
339 //static internal StrongTypingException StrongTyping(string error, Exception innerException) {
340 // StrongTypingException e = new StrongTypingException(error, innerException);
341 // TraceExceptionAsReturnValue(e);
344 #region Query Exceptions
346 /// EntityException factory method
348 /// <param name="message"></param>
349 /// <returns>EntityException</returns>
350 static internal EntitySqlException EntitySqlError( string message )
352 return new EntitySqlException(message);
356 /// EntityException factory method
358 /// <param name="message"></param>
359 /// <param name="innerException"></param>
360 /// <returns></returns>
361 static internal EntitySqlException EntitySqlError( string message, Exception innerException)
363 return new EntitySqlException(message, innerException);
367 /// EntityException factory method
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 )
374 return EntitySqlException.Create(errCtx, message, null);
378 /// EntityException factory method
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 )
385 return EntitySqlException.Create(errCtx, message, null);
389 /// EntityException factory method
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 )
397 return EntitySqlException.Create(queryText, errorMessage, errorPosition, null, false, null);
401 /// EntityException factory method. AdditionalErrorInformation will be used inlined if loadContextInfoFromResource is false.
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,
412 string additionalErrorInformation,
413 bool loadContextInfoFromResource )
415 return EntitySqlException.Create(queryText,
418 additionalErrorInformation,
419 loadContextInfoFromResource,
424 #region Bridge Errors
425 static internal ProviderIncompatibleException CannotCloneStoreProvider() {
426 return ProviderIncompatible(System.Data.Entity.Strings.EntityClient_CannotCloneStoreProvider);
428 static internal InvalidOperationException ClosedDataReaderError() {
429 return InvalidOperation(System.Data.Entity.Strings.ADP_ClosedDataReaderError);
431 static internal InvalidOperationException DataReaderClosed(string method) {
432 return InvalidOperation(System.Data.Entity.Strings.ADP_DataReaderClosed(method));
434 static internal InvalidOperationException ImplicitlyClosedDataReaderError() {
435 return InvalidOperation(System.Data.Entity.Strings.ADP_ImplicitlyClosedDataReaderError);
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)));
440 static internal IndexOutOfRangeException InvalidDataLength(long length) {
441 return IndexOutOfRange(System.Data.Entity.Strings.ADP_InvalidDataLength(length.ToString(CultureInfo.InvariantCulture)));
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);
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);
449 static internal InvalidOperationException MustUseSequentialAccess() {
450 return InvalidOperation(System.Data.Entity.Strings.ADP_MustUseSequentialAccess);
452 static internal InvalidOperationException NoData() {
453 return InvalidOperation(System.Data.Entity.Strings.ADP_NoData);
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));
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)));
461 static internal NotSupportedException KeysRequiredForJoinOverNest(Query.InternalTrees.Op op) {
462 return NotSupported(System.Data.Entity.Strings.ADP_KeysRequiredForJoinOverNest(op.OpType.ToString()));
464 static internal NotSupportedException KeysRequiredForNesting() {
465 return NotSupported(System.Data.Entity.Strings.ADP_KeysRequiredForNesting);
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()));
470 static internal NotSupportedException ProviderDoesNotSupportCommandTrees() {
471 return NotSupported(System.Data.Entity.Strings.ADP_ProviderDoesNotSupportCommandTrees);
473 static internal EntityCommandExecutionException CommandExecutionDataReaderFieldCountForScalarType() {
474 return CommandExecution(System.Data.Entity.Strings.ADP_InvalidDataReaderFieldCountForScalarType);
476 static internal EntityCommandExecutionException CommandExecutionDataReaderMissingColumnForType(EdmMember member, EdmType currentType) {
477 return CommandExecution(System.Data.Entity.Strings.ADP_InvalidDataReaderMissingColumnForType(
478 currentType.FullName, member.Name));
480 static internal EntityCommandExecutionException CommandExecutionDataReaderMissinDiscriminatorColumn(string columnName, EdmFunction functionImport) {
481 return CommandExecution(System.Data.Entity.Strings.ADP_InvalidDataReaderMissingDiscriminatorColumn(columnName, functionImport.FullName));
486 #region EntityClient Errors
487 static internal ProviderIncompatibleException ProviderIncompatible(string error) {
488 return new ProviderIncompatibleException(error);
490 static internal ProviderIncompatibleException ProviderIncompatible(string error, Exception innerException) {
491 return new ProviderIncompatibleException(error, innerException);
493 static internal EntityException Provider(string error) {
494 return new EntityException(error);
496 static internal EntityException Provider(Exception inner) {
497 return new EntityException(System.Data.Entity.Strings.EntityClient_ProviderGeneralError, inner);
499 static internal EntityException Provider(string parameter, Exception inner) {
500 return new EntityException(System.Data.Entity.Strings.EntityClient_ProviderSpecificError(parameter), inner);
502 static internal EntityException ProviderExceptionWithMessage(string message, Exception inner) {
503 return new EntityException(message, inner);
505 #endregion //EntityClient Errors
507 #region SqlClient Errors
509 static internal InvalidOperationException SqlTypesAssemblyNotFound()
511 return InvalidOperation(System.Data.Entity.Strings.SqlProvider_SqlTypesAssemblyNotFound);
514 static internal ProviderIncompatibleException GeographyValueNotSqlCompatible()
516 return ProviderIncompatible(System.Data.Entity.Strings.SqlProvider_GeographyValueNotSqlCompatible);
519 static internal ProviderIncompatibleException GeometryValueNotSqlCompatible()
521 return ProviderIncompatible(System.Data.Entity.Strings.SqlProvider_GeometryValueNotSqlCompatible);
524 #endregion //SqlClient Errors
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));
534 static internal MetadataException InvalidCollectionForMapping(DataSpace space) {
535 return Metadata(System.Data.Entity.Strings.InvalidCollectionForMapping(space.ToString()));
537 // MemberCollection.cs
538 static internal ArgumentException MemberInvalidIdentity(string identity, string parameter) {
539 return Argument(System.Data.Entity.Strings.MemberInvalidIdentity(identity), parameter);
541 // MetadataCollection.cs
542 static internal ArgumentException ArrayTooSmall(string parameter) {
543 return Argument(System.Data.Entity.Strings.ArrayTooSmall, parameter);
545 static internal ArgumentException ItemDuplicateIdentity(string identity, string parameter, Exception inner) {
546 return Argument(System.Data.Entity.Strings.ItemDuplicateIdentity(identity), parameter, inner);
548 static internal ArgumentException ItemInvalidIdentity(string identity, string parameter) {
549 return Argument(System.Data.Entity.Strings.ItemInvalidIdentity(identity), parameter);
551 static internal InvalidOperationException MoreThanOneItemMatchesIdentity(string identity) {
552 return InvalidOperation(System.Data.Entity.Strings.MoreThanOneItemMatchesIdentity(identity));
554 static internal InvalidOperationException OperationOnReadOnlyCollection() {
555 return InvalidOperation(System.Data.Entity.Strings.OperationOnReadOnlyCollection);
557 // MetadataWorkspace.cs
558 static internal InvalidOperationException ItemCollectionAlreadyRegistered(DataSpace space) {
559 return InvalidOperation(System.Data.Entity.Strings.ItemCollectionAlreadyRegistered(space.ToString()));
561 static internal InvalidOperationException NoCollectionForSpace(DataSpace space) {
562 return InvalidOperation(System.Data.Entity.Strings.NoCollectionForSpace(space.ToString()));
564 static internal InvalidOperationException InvalidCollectionSpecified(DataSpace space) {
565 return InvalidOperation(System.Data.Entity.Strings.InvalidCollectionSpecified(space));
567 static internal MetadataException DifferentSchemaVersionInCollection(string itemCollectionType, double versionToRegister, double currentSchemaVersion)
569 return Metadata(Strings.DifferentSchemaVersionInCollection(itemCollectionType, versionToRegister, currentSchemaVersion));
572 static internal ArgumentException NotBinaryTypeForTypeUsage() {
573 return Argument(System.Data.Entity.Strings.NotBinaryTypeForTypeUsage);
575 static internal ArgumentException NotDateTimeTypeForTypeUsage() {
576 return Argument(System.Data.Entity.Strings.NotDateTimeTypeForTypeUsage);
578 static internal ArgumentException NotDateTimeOffsetTypeForTypeUsage()
580 return Argument(System.Data.Entity.Strings.NotDateTimeOffsetTypeForTypeUsage);
582 static internal ArgumentException NotTimeTypeForTypeUsage()
584 return Argument(System.Data.Entity.Strings.NotTimeTypeForTypeUsage);
586 static internal ArgumentException NotDecimalTypeForTypeUsage() {
587 return Argument(System.Data.Entity.Strings.NotDecimalTypeForTypeUsage);
589 static internal ArgumentException NotStringTypeForTypeUsage() {
590 return Argument(System.Data.Entity.Strings.NotStringTypeForTypeUsage);
592 // EntityContainer.cs
593 static internal ArgumentException InvalidEntitySetName(string name) {
594 return Argument(System.Data.Entity.Strings.InvalidEntitySetName(name));
596 static internal ArgumentException InvalidRelationshipSetName(string name) {
597 return Argument(System.Data.Entity.Strings.InvalidRelationshipSetName(name));
599 static internal ArgumentException InvalidEDMVersion(double edmVersion)
601 return Argument(System.Data.Entity.Strings.InvalidEDMVersion(edmVersion.ToString(CultureInfo.CurrentCulture)));
604 // EntitySetBaseCollection.cs
605 static internal ArgumentException EntitySetInAnotherContainer(string parameter) {
606 return Argument(System.Data.Entity.Strings.EntitySetInAnotherContainer, parameter);
609 static internal InvalidOperationException OperationOnReadOnlyItem() {
610 return InvalidOperation(System.Data.Entity.Strings.OperationOnReadOnlyItem);
612 //FacetDescription.cs
613 static internal ArgumentException MinAndMaxValueMustBeSameForConstantFacet(string facetName, string typeName) {
614 return Argument(System.Data.Entity.Strings.MinAndMaxValueMustBeSameForConstantFacet(facetName, typeName));
616 static internal ArgumentException MissingDefaultValueForConstantFacet(string facetName, string typeName) {
617 return Argument(System.Data.Entity.Strings.MissingDefaultValueForConstantFacet(facetName, typeName));
619 static internal ArgumentException BothMinAndMaxValueMustBeSpecifiedForNonConstantFacet(string facetName, string typeName) {
620 return Argument(System.Data.Entity.Strings.BothMinAndMaxValueMustBeSpecifiedForNonConstantFacet(facetName, typeName));
622 static internal ArgumentException MinAndMaxValueMustBeDifferentForNonConstantFacet(string facetName, string typeName) {
623 return Argument(System.Data.Entity.Strings.MinAndMaxValueMustBeDifferentForNonConstantFacet(facetName, typeName));
625 static internal ArgumentException MinAndMaxMustBePositive(string facetName, string typeName) {
626 return Argument(System.Data.Entity.Strings.MinAndMaxMustBePositive(facetName, typeName));
628 static internal ArgumentException MinMustBeLessThanMax(string minimumValue, string facetName, string typeName) {
629 return Argument(System.Data.Entity.Strings.MinMustBeLessThanMax(minimumValue, facetName, typeName));
631 static internal ArgumentException EntitySetNotInCSpace(string name) {
632 return Argument(System.Data.Entity.Strings.EntitySetNotInCSPace(name));
635 static internal ArgumentException TypeNotInEntitySet(string entitySetName, string rootEntityTypeName, string entityTypeName) {
636 return Argument(System.Data.Entity.Strings.TypeNotInEntitySet(entityTypeName, rootEntityTypeName, entitySetName));
639 static internal ArgumentException AssociationSetNotInCSpace(string name) {
640 return Argument(System.Data.Entity.Strings.EntitySetNotInCSPace(name));
643 static internal ArgumentException TypeNotInAssociationSet(string setName, string rootEntityTypeName, string typeName) {
644 return Argument(System.Data.Entity.Strings.TypeNotInAssociationSet(typeName, rootEntityTypeName, setName));
646 #endregion //Metadata Errors
648 #region Internal Errors
650 // Internal error code to use with the InternalError exception.
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.
655 // The acceptable range for this enum is
658 // The Range 10,000-15,000 is reserved for tools
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,
666 ColumnCountMismatch = 1003,
669 /// Some assertion failed
671 AssertionFailed = 1004,
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,
685 /// Thrown when SQL gen produces parameters for anything other than a
686 /// modification command tree.
688 SqlGenParametersNotPermitted = 1017,
689 EntityKeyMissingKeyValue = 1018,
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.).
694 UpdatePipelineResultRequestInvalid = 1019,
695 InvalidStateEntry = 1020,
697 /// Thrown when the update pipeline encounters an invalid PrimitiveTypeKind
700 InvalidPrimitiveTypeKind = 1021,
702 /// Thrown when an unknown node type is encountered in ELinq expression translation.
704 UnknownLinqNodeType = 1023,
706 /// Thrown by result assembly upon encountering a collection column that does not use any columns
707 /// nor has a descriminated nested collection.
709 CollectionWithNoColumns = 1024,
711 /// Thrown when a lambda expression argument has an unexpected node type.
713 UnexpectedLinqLambdaExpressionFormat = 1025,
715 /// Thrown when a CommandTree is defined on a stored procedure EntityCommand instance.
717 CommandTreeOnStoredProcedureEntityCommand = 1026,
719 /// Thrown when an operation in the BoolExpr library is exceeding anticipated complexity.
721 BoolExprAssert = 1027,
722 // AttemptToGenerateDefinitionForFunctionWithoutDef = 1028,
724 /// Thrown when type A is promotable to type B, but ranking algorithm fails to rank the promotion.
726 FailedToGeneratePromotionRank = 1029,
729 static internal Exception InternalError(InternalErrorCode internalError) {
730 return InvalidOperation(System.Data.Entity.Strings.ADP_InternalProviderError((int)internalError));
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);
739 return InvalidOperation(System.Data.Entity.Strings.ADP_InternalProviderError(sb.ToString()));
742 static internal Exception InternalError(InternalErrorCode internalError, int location) {
743 return InternalError(internalError, location, null);
748 #region ObjectStateManager errors
749 internal static InvalidOperationException OriginalValuesDoesNotExist() {
750 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateEntry_OriginalValuesDoesNotExist);
753 internal static InvalidOperationException CurrentValuesDoesNotExist() {
754 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateEntry_CurrentValuesDoesNotExist);
757 internal static ArgumentException InvalidTypeForComplexTypeProperty(string argument) {
758 return EntityUtil.Argument(System.Data.Entity.Strings.ObjectStateEntry_InvalidTypeForComplexTypeProperty, argument);
761 internal static InvalidOperationException ObjectStateEntryinInvalidState() {
762 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateEntry_InvalidState);
765 internal static InvalidOperationException CantModifyDetachedDeletedEntries() {
766 throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateEntry_CantModifyDetachedDeletedEntries);
769 internal static InvalidOperationException SetModifiedStates(string methodName)
771 throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateEntry_SetModifiedStates(methodName));
774 internal static InvalidOperationException EntityCantHaveMultipleChangeTrackers() {
775 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.Entity_EntityCantHaveMultipleChangeTrackers);
778 internal static InvalidOperationException CantModifyRelationValues() {
779 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateEntry_CantModifyRelationValues);
782 internal static InvalidOperationException CantModifyRelationState() {
783 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateEntry_CantModifyRelationState);
786 internal static InvalidOperationException CannotModifyKeyProperty(string fieldName) {
787 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateEntry_CannotModifyKeyProperty(fieldName));
790 internal static InvalidOperationException CantSetEntityKey() {
791 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateEntry_CantSetEntityKey);
794 internal static InvalidOperationException CannotAccessKeyEntryValues() {
795 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateEntry_CannotAccessKeyEntryValues);
798 internal static InvalidOperationException CannotModifyKeyEntryState() {
799 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateEntry_CannotModifyKeyEntryState);
803 internal static InvalidOperationException CannotCallDeleteOnKeyEntry() {
804 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateEntry_CannotDeleteOnKeyEntry);
807 internal static ArgumentException InvalidModifiedPropertyName(string propertyName) {
808 return EntityUtil.Argument(System.Data.Entity.Strings.ObjectStateEntry_SetModifiedOnInvalidProperty(propertyName));
810 internal static InvalidOperationException NoEntryExistForEntityKey() {
811 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateManager_NoEntryExistForEntityKey);
813 internal static ArgumentException DetachedObjectStateEntriesDoesNotExistInObjectStateManager() {
814 return EntityUtil.Argument(System.Data.Entity.Strings.ObjectStateManager_DetachedObjectStateEntriesDoesNotExistInObjectStateManager);
817 internal static InvalidOperationException ObjectStateManagerContainsThisEntityKey() {
818 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateManager_ObjectStateManagerContainsThisEntityKey);
820 internal static InvalidOperationException ObjectStateManagerDoesnotAllowToReAddUnchangedOrModifiedOrDeletedEntity(EntityState state) {
821 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateManager_DoesnotAllowToReAddUnchangedOrModifiedOrDeletedEntity(state));
823 internal static InvalidOperationException CannotFixUpKeyToExistingValues() {
824 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateManager_CannotFixUpKeyToExistingValues);
826 internal static InvalidOperationException KeyPropertyDoesntMatchValueInKey(bool forAttach)
830 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateManager_KeyPropertyDoesntMatchValueInKeyForAttach);
834 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateManager_KeyPropertyDoesntMatchValueInKey);
838 internal static void CheckValidStateForChangeEntityState(EntityState state)
842 case EntityState.Added:
843 case EntityState.Unchanged:
844 case EntityState.Modified:
845 case EntityState.Deleted:
846 case EntityState.Detached:
849 throw InvalidEntityStateArgument("state");
853 internal static void CheckValidStateForChangeRelationshipState(EntityState state, string paramName)
857 case EntityState.Added:
858 case EntityState.Unchanged:
859 case EntityState.Deleted:
860 case EntityState.Detached:
863 throw InvalidRelationshipStateArgument(paramName);
867 internal static InvalidOperationException InvalidKey() {
868 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateManager_InvalidKey);
870 internal static InvalidOperationException AcceptChangesEntityKeyIsNotValid() {
871 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateManager_AcceptChangesEntityKeyIsNotValid);
873 internal static InvalidOperationException EntityConflictsWithKeyEntry() {
874 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateManager_EntityConflictsWithKeyEntry);
876 internal static InvalidOperationException ObjectDoesNotHaveAKey(object entity) {
877 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateManager_GetEntityKeyRequiresObjectToHaveAKey(entity.GetType().FullName));
879 internal static InvalidOperationException EntityValueChangedWithoutEntityValueChanging() {
880 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateEntry_EntityMemberChangedWithoutEntityMemberChanging);
882 internal static InvalidOperationException ChangedInDifferentStateFromChanging(EntityState currentState, EntityState previousState) {
883 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateEntry_ChangedInDifferentStateFromChanging(previousState, currentState));
885 internal static ArgumentException ChangeOnUnmappedProperty(string entityPropertyName) {
886 return EntityUtil.Argument(System.Data.Entity.Strings.ObjectStateEntry_ChangeOnUnmappedProperty(entityPropertyName));
889 internal static ArgumentException ChangeOnUnmappedComplexProperty(string complexPropertyName) {
890 return EntityUtil.Argument(System.Data.Entity.Strings.ObjectStateEntry_ChangeOnUnmappedComplexProperty(complexPropertyName));
893 internal static ArgumentException EntityTypeDoesNotMatchEntitySet(string entityType, string entitysetName, string argument) {
894 return Argument(System.Data.Entity.Strings.ObjectStateManager_EntityTypeDoesnotMatchtoEntitySetType(entityType, entitysetName), argument);
896 internal static InvalidOperationException NoEntryExistsForObject(object entity)
898 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateManager_NoEntryExistsForObject(entity.GetType().FullName));
900 internal static InvalidOperationException EntityNotTracked()
902 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectStateManager_EntityNotTracked);
904 internal static InvalidOperationException SetOriginalComplexProperties(string propertyName)
906 return InvalidOperation(Strings.ObjectStateEntry_SetOriginalComplexProperties(propertyName));
908 internal static InvalidOperationException NullOriginalValueForNonNullableProperty(string propertyName, string clrMemberName, string clrTypeName)
910 return InvalidOperation(Strings.ObjectStateEntry_NullOriginalValueForNonNullableProperty(propertyName, clrMemberName, clrTypeName));
912 internal static InvalidOperationException SetOriginalPrimaryKey(string propertyName)
914 return InvalidOperation(Strings.ObjectStateEntry_SetOriginalPrimaryKey(propertyName));
919 #region ObjectMaterializer errors
921 internal static void ThrowPropertyIsNotNullable(string propertyName)
923 if (String.IsNullOrEmpty(propertyName))
926 throw EntityUtil.Constraint(
927 System.Data.Entity.Strings.Materializer_PropertyIsNotNullable);
931 throw EntityUtil.PropertyConstraint(
932 System.Data.Entity.Strings.Materializer_PropertyIsNotNullableWithName(propertyName), propertyName);
936 internal static void ThrowSetInvalidValue(object value, Type destinationType, string className, string propertyName)
940 throw EntityUtil.Constraint(
941 System.Data.Entity.Strings.Materializer_SetInvalidValue(
942 (Nullable.GetUnderlyingType(destinationType) ?? destinationType).Name,
943 className, propertyName, "null"));
947 throw EntityUtil.InvalidOperation(
948 System.Data.Entity.Strings.Materializer_SetInvalidValue(
949 (Nullable.GetUnderlyingType(destinationType) ?? destinationType).Name,
950 className, propertyName, value.GetType().Name));
953 internal static InvalidOperationException ValueInvalidCast(Type valueType, Type destinationType)
955 Debug.Assert(null != valueType, "null valueType");
956 Debug.Assert(null != destinationType, "null destinationType");
957 if (destinationType.IsValueType && destinationType.IsGenericType && (typeof(Nullable<>) == destinationType.GetGenericTypeDefinition()))
959 return EntityUtil.InvalidOperation(
960 System.Data.Entity.Strings.Materializer_InvalidCastNullable(
961 valueType, destinationType.GetGenericArguments()[0]));
965 return EntityUtil.InvalidOperation(
966 System.Data.Entity.Strings.Materializer_InvalidCastReference(
967 valueType, destinationType));
970 internal static InvalidOperationException ValueNullReferenceCast(Type destinationType)
972 Debug.Assert(null != destinationType, "null value");
973 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.Materializer_NullReferenceCast(destinationType.Name));
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()));
979 internal static InvalidOperationException AddedEntityAlreadyExists(EntityKey key) {
980 return InvalidOperation(System.Data.Entity.Strings.Materializer_AddedEntityAlreadyExists(key.ConcatKeyValue()));
982 internal static InvalidOperationException CannotReEnumerateQueryResults() {
983 return InvalidOperation(System.Data.Entity.Strings.Materializer_CannotReEnumerateQueryResults);
985 internal static NotSupportedException MaterializerUnsupportedType() {
986 return NotSupported(System.Data.Entity.Strings.Materializer_UnsupportedType);
990 #region ObjectView errors
991 internal static InvalidOperationException CannotReplacetheEntityorRow() {
992 return InvalidOperation(System.Data.Entity.Strings.ObjectView_CannotReplacetheEntityorRow);
994 internal static NotSupportedException IndexBasedInsertIsNotSupported() {
995 return NotSupported(System.Data.Entity.Strings.ObjectView_IndexBasedInsertIsNotSupported);
997 internal static InvalidOperationException WriteOperationNotAllowedOnReadOnlyBindingList() {
998 return InvalidOperation(System.Data.Entity.Strings.ObjectView_WriteOperationNotAllowedOnReadOnlyBindingList);
1000 internal static InvalidOperationException AddNewOperationNotAllowedOnAbstractBindingList() {
1001 return InvalidOperation(System.Data.Entity.Strings.ObjectView_AddNewOperationNotAllowedOnAbstractBindingList);
1003 internal static ArgumentException IncompatibleArgument() {
1004 return Argument(System.Data.Entity.Strings.ObjectView_IncompatibleArgument);
1006 internal static InvalidOperationException CannotResolveTheEntitySetforGivenEntity(Type type) {
1007 return InvalidOperation(System.Data.Entity.Strings.ObjectView_CannotResolveTheEntitySet(type.FullName));
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));
1019 internal static InvalidOperationException ExpectedCollectionGotReference(string typeName, string roleName, string relationshipName) {
1020 return InvalidOperation(System.Data.Entity.Strings.Collections_ExpectedCollectionGotReference(typeName, roleName, relationshipName));
1022 internal static InvalidOperationException CannotFillTryDifferentMergeOption(string relationshipName, string roleName) {
1023 return InvalidOperation(Strings.Collections_CannotFillTryDifferentMergeOption(relationshipName, roleName));
1025 internal static InvalidOperationException CannotRemergeCollections() {
1026 return InvalidOperation(System.Data.Entity.Strings.Collections_UnableToMergeCollections);
1028 internal static InvalidOperationException ExpectedReferenceGotCollection(string typeName, string roleName, string relationshipName) {
1029 return InvalidOperation(System.Data.Entity.Strings.EntityReference_ExpectedReferenceGotCollection(typeName, roleName, relationshipName));
1031 internal static InvalidOperationException CannotAddMoreThanOneEntityToEntityReference(string roleName, string relationshipName) {
1032 return InvalidOperation(System.Data.Entity.Strings.EntityReference_CannotAddMoreThanOneEntityToEntityReference(roleName, relationshipName));
1034 internal static ArgumentException CannotSetSpecialKeys() {
1035 return Argument(System.Data.Entity.Strings.EntityReference_CannotSetSpecialKeys, "value");
1037 internal static InvalidOperationException EntityKeyValueMismatch() {
1038 return InvalidOperation(System.Data.Entity.Strings.EntityReference_EntityKeyValueMismatch);
1040 internal static InvalidOperationException RelatedEndNotAttachedToContext(string relatedEndType) {
1041 return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_RelatedEndNotAttachedToContext(relatedEndType));
1043 internal static InvalidOperationException CannotCreateRelationshipBetweenTrackedAndNoTrackedEntities(string roleName) {
1044 return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_CannotCreateRelationshipBetweenTrackedAndNoTrackedEntities(roleName));
1046 internal static InvalidOperationException CannotCreateRelationshipEntitiesInDifferentContexts() {
1047 return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_CannotCreateRelationshipEntitiesInDifferentContexts);
1049 internal static InvalidOperationException InvalidContainedTypeCollection(string entityType, string relatedEndType) {
1050 return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_InvalidContainedType_Collection(entityType, relatedEndType));
1052 internal static InvalidOperationException InvalidContainedTypeReference(string entityType, string relatedEndType) {
1053 return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_InvalidContainedType_Reference(entityType, relatedEndType));
1055 internal static InvalidOperationException CannotAddToFixedSizeArray(object collectionType) {
1056 return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_CannotAddToFixedSizeArray(collectionType.GetType()));
1058 internal static InvalidOperationException CannotRemoveFromFixedSizeArray(object collectionType) {
1059 return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_CannotRemoveFromFixedSizeArray(collectionType.GetType()));
1061 internal static InvalidOperationException OwnerIsNull() {
1062 return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_OwnerIsNull);
1064 internal static InvalidOperationException UnableToAddRelationshipWithDeletedEntity() {
1065 return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_UnableToAddRelationshipWithDeletedEntity);
1067 internal static InvalidOperationException ConflictingChangeOfRelationshipDetected() {
1068 return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_ConflictingChangeOfRelationshipDetected);
1070 internal static InvalidOperationException InvalidRelationshipFixupDetected(string propertyName, string entityType) {
1071 return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_InvalidRelationshipFixupDetected(propertyName, entityType));
1073 internal static InvalidOperationException LessThanExpectedRelatedEntitiesFound()
1075 return InvalidOperation(System.Data.Entity.Strings.EntityReference_LessThanExpectedRelatedEntitiesFound);
1077 internal static InvalidOperationException MoreThanExpectedRelatedEntitiesFound() {
1078 return InvalidOperation(System.Data.Entity.Strings.EntityReference_MoreThanExpectedRelatedEntitiesFound);
1080 internal static InvalidOperationException CannotChangeReferentialConstraintProperty() {
1081 return InvalidOperation(System.Data.Entity.Strings.EntityReference_CannotChangeReferentialConstraintProperty);
1083 internal static InvalidOperationException RelatedEndNotFound() {
1084 return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_RelatedEndNotFound);
1086 internal static InvalidOperationException LoadCalledOnNonEmptyNoTrackedRelatedEnd() {
1087 return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_LoadCalledOnNonEmptyNoTrackedRelatedEnd);
1089 internal static InvalidOperationException LoadCalledOnAlreadyLoadedNoTrackedRelatedEnd() {
1090 return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_LoadCalledOnAlreadyLoadedNoTrackedRelatedEnd);
1092 internal static InvalidOperationException MismatchedMergeOptionOnLoad(MergeOption mergeOption) {
1093 return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_MismatchedMergeOptionOnLoad(mergeOption));
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));
1098 internal static InvalidOperationException UnableToRetrieveReferentialConstraintProperties() {
1099 return InvalidOperation(System.Data.Entity.Strings.RelationshipManager_UnableToRetrieveReferentialConstraintProperties);
1101 internal static InvalidOperationException InconsistentReferentialConstraintProperties() {
1102 return InvalidOperation(System.Data.Entity.Strings.RelationshipManager_InconsistentReferentialConstraintProperties);
1104 internal static InvalidOperationException CircularRelationshipsWithReferentialConstraints() {
1105 return InvalidOperation(System.Data.Entity.Strings.RelationshipManager_CircularRelationshipsWithReferentialConstraints);
1107 internal static ArgumentException UnableToFindRelationshipTypeInMetadata(string relationshipName, string parameterName) {
1108 return Argument(System.Data.Entity.Strings.RelationshipManager_UnableToFindRelationshipTypeInMetadata(relationshipName), parameterName);
1110 internal static ArgumentException InvalidTargetRole(string relationshipName, string targetRoleName, string parameterName) {
1111 return Argument(System.Data.Entity.Strings.RelationshipManager_InvalidTargetRole(relationshipName, targetRoleName), parameterName);
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));
1116 internal static InvalidOperationException UnexpectedNullContext() {
1117 return InvalidOperation(System.Data.Entity.Strings.RelationshipManager_UnexpectedNullContext);
1119 internal static InvalidOperationException ReferenceAlreadyInitialized() {
1120 return InvalidOperation(System.Data.Entity.Strings.RelationshipManager_ReferenceAlreadyInitialized(System.Data.Entity.Strings.RelationshipManager_InitializeIsForDeserialization));
1122 internal static InvalidOperationException RelationshipManagerAttached() {
1123 return InvalidOperation(System.Data.Entity.Strings.RelationshipManager_RelationshipManagerAttached(System.Data.Entity.Strings.RelationshipManager_InitializeIsForDeserialization));
1125 internal static InvalidOperationException CollectionAlreadyInitialized() {
1126 return InvalidOperation(System.Data.Entity.Strings.RelationshipManager_CollectionAlreadyInitialized(System.Data.Entity.Strings.RelationshipManager_CollectionInitializeIsForDeserialization));
1128 internal static InvalidOperationException CollectionRelationshipManagerAttached() {
1129 return InvalidOperation(System.Data.Entity.Strings.RelationshipManager_CollectionRelationshipManagerAttached(System.Data.Entity.Strings.RelationshipManager_CollectionInitializeIsForDeserialization));
1131 internal static void CheckContextNull(ObjectContext context)
1133 if ((object)context == null)
1135 throw EntityUtil.UnexpectedNullContext();
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:
1147 throw EntityUtil.InvalidMergeOption(mergeOption);
1150 internal static void CheckArgumentRefreshMode(RefreshMode refreshMode) {
1151 switch(refreshMode) {
1152 case RefreshMode.ClientWins:
1153 case RefreshMode.StoreWins:
1156 throw EntityUtil.InvalidRefreshMode(refreshMode);
1159 internal static InvalidOperationException InvalidEntityStateSource() {
1160 return InvalidOperation(System.Data.Entity.Strings.Collections_InvalidEntityStateSource);
1162 internal static InvalidOperationException InvalidEntityStateLoad(string relatedEndType) {
1163 return InvalidOperation(System.Data.Entity.Strings.Collections_InvalidEntityStateLoad(relatedEndType));
1165 internal static InvalidOperationException InvalidOwnerStateForAttach() {
1166 return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_InvalidOwnerStateForAttach);
1168 internal static InvalidOperationException InvalidNthElementNullForAttach(int index) {
1169 return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_InvalidNthElementNullForAttach(index));
1171 internal static InvalidOperationException InvalidNthElementContextForAttach(int index) {
1172 return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_InvalidNthElementContextForAttach(index));
1174 internal static InvalidOperationException InvalidNthElementStateForAttach(int index) {
1175 return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_InvalidNthElementStateForAttach(index));
1177 internal static InvalidOperationException InvalidEntityContextForAttach() {
1178 return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_InvalidEntityContextForAttach);
1180 internal static InvalidOperationException InvalidEntityStateForAttach() {
1181 return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_InvalidEntityStateForAttach);
1183 internal static InvalidOperationException UnableToAddToDisconnectedRelatedEnd() {
1184 return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_UnableToAddEntity);
1186 internal static InvalidOperationException UnableToRemoveFromDisconnectedRelatedEnd() {
1187 return InvalidOperation(System.Data.Entity.Strings.RelatedEnd_UnableToRemoveEntity);
1189 internal static InvalidOperationException ProxyMetadataIsUnavailable(Type type, Exception inner) {
1190 return InvalidOperation(System.Data.Entity.Strings.EntityProxyTypeInfo_ProxyMetadataIsUnavailable(type.FullName), inner);
1192 internal static InvalidOperationException DuplicateTypeForProxyType(Type type) {
1193 return InvalidOperation(System.Data.Entity.Strings.EntityProxyTypeInfo_DuplicateOSpaceType(type.FullName));
1197 #region ObjectContext errors
1198 internal static InvalidOperationException ClientEntityRemovedFromStore(string entitiesKeys) {
1199 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectContext_ClientEntityRemovedFromStore(entitiesKeys));
1201 internal static InvalidOperationException StoreEntityNotPresentInClient() {
1202 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectContext_StoreEntityNotPresentInClient);
1204 internal static InvalidOperationException ContextMetadataHasChanged() {
1205 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectContext_MetadataHasChanged);
1207 internal static ArgumentException InvalidConnection(bool isConnectionConstructor, Exception innerException)
1209 if (isConnectionConstructor)
1211 return InvalidConnection("connection", innerException);
1215 return InvalidConnectionString("connectionString", innerException);
1218 internal static ArgumentException InvalidConnectionString(string parameter, Exception inner) {
1219 return EntityUtil.Argument(System.Data.Entity.Strings.ObjectContext_InvalidConnectionString, parameter, inner);
1221 internal static ArgumentException InvalidConnection(string parameter, Exception inner) {
1222 return EntityUtil.Argument(System.Data.Entity.Strings.ObjectContext_InvalidConnection, parameter, inner);
1224 internal static InvalidOperationException InvalidDataAdapter() {
1225 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectContext_InvalidDataAdapter);
1227 internal static ArgumentException InvalidDefaultContainerName(string parameter, string defaultContainerName) {
1228 return EntityUtil.Argument(System.Data.Entity.Strings.ObjectContext_InvalidDefaultContainerName(defaultContainerName), parameter);
1230 internal static InvalidOperationException NthElementInAddedState(int i) {
1231 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectContext_NthElementInAddedState(i));
1233 internal static InvalidOperationException NthElementIsDuplicate(int i) {
1234 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectContext_NthElementIsDuplicate(i));
1236 internal static InvalidOperationException NthElementIsNull(int i) {
1237 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectContext_NthElementIsNull(i));
1239 internal static InvalidOperationException NthElementNotInObjectStateManager(int i) {
1240 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectContext_NthElementNotInObjectStateManager(i));
1242 internal static ObjectDisposedException ObjectContextDisposed() {
1243 return EntityUtil.ObjectDisposed(System.Data.Entity.Strings.ObjectContext_ObjectDisposed);
1245 internal static ObjectNotFoundException ObjectNotFound() {
1246 return EntityUtil.ObjectNotFound(System.Data.Entity.Strings.ObjectContext_ObjectNotFound);
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));
1252 internal static InvalidOperationException CannotDeleteEntityNotInObjectStateManager() {
1253 return InvalidOperation(System.Data.Entity.Strings.ObjectContext_CannotDeleteEntityNotInObjectStateManager);
1255 internal static InvalidOperationException CannotDetachEntityNotInObjectStateManager() {
1256 return InvalidOperation(System.Data.Entity.Strings.ObjectContext_CannotDetachEntityNotInObjectStateManager);
1258 internal static InvalidOperationException EntitySetNotFoundForName(string entitySetName) {
1259 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectContext_EntitySetNotFoundForName(entitySetName));
1261 internal static InvalidOperationException EntityContainterNotFoundForName(string entityContainerName) {
1262 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectContext_EntityContainerNotFoundForName(entityContainerName));
1264 internal static ArgumentException InvalidCommandTimeout(string argument) {
1265 return Argument(System.Data.Entity.Strings.ObjectContext_InvalidCommandTimeout, argument);
1267 internal static InvalidOperationException EntityAlreadyExistsInObjectStateManager() {
1268 return InvalidOperation(System.Data.Entity.Strings.ObjectContext_EntityAlreadyExistsInObjectStateManager);
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));
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));
1276 internal static InvalidOperationException CannotAttachEntityWithoutKey() {
1277 return InvalidOperation(System.Data.Entity.Strings.ObjectContext_CannotAttachEntityWithoutKey);
1279 internal static InvalidOperationException CannotAttachEntityWithTemporaryKey() {
1280 return InvalidOperation(System.Data.Entity.Strings.ObjectContext_CannotAttachEntityWithTemporaryKey);
1282 internal static InvalidOperationException EntitySetNameOrEntityKeyRequired() {
1283 return InvalidOperation(System.Data.Entity.Strings.ObjectContext_EntitySetNameOrEntityKeyRequired);
1285 internal static InvalidOperationException ExecuteFunctionTypeMismatch(Type typeArgument, EdmType expectedElementType) {
1286 return InvalidOperation(System.Data.Entity.Strings.ObjectContext_ExecuteFunctionTypeMismatch(
1287 typeArgument.FullName,
1288 expectedElementType.FullName));
1290 internal static InvalidOperationException ExecuteFunctionCalledWithNonReaderFunction(EdmFunction functionImport) {
1291 // report ExecuteNonQuery return type if no explicit return type is given
1293 if (null == functionImport.ReturnParameter)
1295 message = System.Data.Entity.Strings.ObjectContext_ExecuteFunctionCalledWithNonQueryFunction(
1296 functionImport.Name);
1300 message = System.Data.Entity.Strings.ObjectContext_ExecuteFunctionCalledWithScalarFunction(
1301 functionImport.ReturnParameter.TypeUsage.EdmType.FullName, functionImport.Name);
1303 return InvalidOperation(message);
1305 internal static ArgumentException QualfiedEntitySetName(string parameterName) {
1306 return Argument(System.Data.Entity.Strings.ObjectContext_QualfiedEntitySetName, parameterName);
1308 internal static ArgumentException ContainerQualifiedEntitySetNameRequired(string argument) {
1309 return Argument(System.Data.Entity.Strings.ObjectContext_ContainerQualifiedEntitySetNameRequired, argument);
1311 internal static InvalidOperationException CannotSetDefaultContainerName() {
1312 return InvalidOperation(System.Data.Entity.Strings.ObjectContext_CannotSetDefaultContainerName);
1314 internal static ArgumentException EntitiesHaveDifferentType(string originalEntityTypeName, string changedEntityTypeName) {
1315 return Argument(System.Data.Entity.Strings.ObjectContext_EntitiesHaveDifferentType(originalEntityTypeName, changedEntityTypeName));
1317 internal static InvalidOperationException EntityMustBeUnchangedOrModified(EntityState state) {
1318 return InvalidOperation(System.Data.Entity.Strings.ObjectContext_EntityMustBeUnchangedOrModified(state.ToString()));
1320 internal static InvalidOperationException EntityMustBeUnchangedOrModifiedOrDeleted(EntityState state) {
1321 return InvalidOperation(System.Data.Entity.Strings.ObjectContext_EntityMustBeUnchangedOrModifiedOrDeleted(state.ToString()));
1323 internal static InvalidOperationException EntityNotTrackedOrHasTempKey()
1325 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectContext_EntityNotTrackedOrHasTempKey);
1328 internal static InvalidOperationException AcceptAllChangesFailure(Exception e) {
1329 return InvalidOperation(System.Data.Entity.Strings.ObjectContext_AcceptAllChangesFailure(e.Message));
1331 internal static ArgumentException InvalidEntitySetOnEntity(string entitySetName, Type entityType, string parameter) {
1332 return Argument(System.Data.Entity.Strings.ObjectContext_InvalidEntitySetOnEntity(entitySetName, entityType), parameter);
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);
1337 internal static InvalidOperationException RequiredMetadataNotAvailable() {
1338 return InvalidOperation(System.Data.Entity.Strings.ObjectContext_RequiredMetadataNotAvailble);
1341 internal static ArgumentException MultipleEntitySetsFoundInSingleContainer(string entityTypeName, string entityContainerName, string exceptionParameterName) {
1342 return Argument(System.Data.Entity.Strings.ObjectContext_MultipleEntitySetsFoundInSingleContainer(entityTypeName, entityContainerName), exceptionParameterName);
1345 internal static ArgumentException MultipleEntitySetsFoundInAllContainers(string entityTypeName, string exceptionParameterName) {
1346 return Argument(System.Data.Entity.Strings.ObjectContext_MultipleEntitySetsFoundInAllContainers(entityTypeName), exceptionParameterName);
1349 internal static ArgumentException NoEntitySetFoundForType(string entityTypeName, string exceptionParameterName) {
1350 return Argument(System.Data.Entity.Strings.ObjectContext_NoEntitySetFoundForType(entityTypeName), exceptionParameterName);
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));
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));
1360 internal static ArgumentException InvalidRelationshipStateArgument(string paramName)
1362 return new ArgumentException(Strings.ObjectContext_InvalidRelationshipState, paramName);
1365 internal static ArgumentException InvalidEntityStateArgument(string paramName)
1367 return new ArgumentException(Strings.ObjectContext_InvalidEntityState, paramName);
1372 #region Complex Types Errors
1373 // Complex types exceptions
1374 internal static InvalidOperationException NullableComplexTypesNotSupported(string propertyName)
1376 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ComplexObject_NullableComplexTypesNotSupported(propertyName));
1378 internal static InvalidOperationException ComplexObjectAlreadyAttachedToParent()
1380 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.ComplexObject_ComplexObjectAlreadyAttachedToParent);
1382 internal static ArgumentException ComplexChangeRequestedOnScalarProperty(string propertyName)
1384 return EntityUtil.Argument(System.Data.Entity.Strings.ComplexObject_ComplexChangeRequestedOnScalarProperty(propertyName));
1388 internal static ArgumentException SpanPathSyntaxError() {
1389 return Argument(System.Data.Entity.Strings.ObjectQuery_Span_SpanPathSyntaxError);
1393 /// This is only used for Include path argument, thus the parameter name is hardcoded to "path"
1395 /// <returns></returns>
1396 static internal ArgumentException ADP_InvalidMultipartNameDelimiterUsage()
1398 return Argument(System.Data.Entity.Strings.ADP_InvalidMultipartNameDelimiterUsage, "path");
1401 static internal Exception InvalidConnectionOptionValue(string key)
1403 return Argument(System.Data.Entity.Strings.ADP_InvalidConnectionOptionValue(key));
1406 static internal ArgumentException InvalidSizeValue(int value)
1408 return Argument(System.Data.Entity.Strings.ADP_InvalidSizeValue(value.ToString(CultureInfo.InvariantCulture)));
1411 static internal ArgumentException ConnectionStringSyntax(int index)
1413 return Argument(System.Data.Entity.Strings.ADP_ConnectionStringSyntax(index));
1416 internal static InvalidOperationException DataRecordMustBeEntity() {
1417 return InvalidOperation(System.Data.Entity.Strings.EntityKey_DataRecordMustBeEntity);
1419 internal static ArgumentException EntitySetDoesNotMatch(string argument, string entitySetName) {
1420 return Argument(System.Data.Entity.Strings.EntityKey_EntitySetDoesNotMatch(entitySetName), argument);
1422 internal static InvalidOperationException EntityTypesDoNotMatch(string recordType, string entitySetType) {
1423 return InvalidOperation(System.Data.Entity.Strings.EntityKey_EntityTypesDoNotMatch(recordType, entitySetType));
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);
1428 internal static InvalidOperationException IncorrectNumberOfKeyValuePairsInvalidOperation(string typeName, int expectedNumFields, int actualNumFields)
1430 return InvalidOperation(System.Data.Entity.Strings.EntityKey_IncorrectNumberOfKeyValuePairs(typeName, expectedNumFields, actualNumFields));
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);
1435 internal static InvalidOperationException IncorrectValueTypeInvalidOperation(string keyField, string expectedTypeName, string actualTypeName) {
1436 return InvalidOperation(System.Data.Entity.Strings.EntityKey_IncorrectValueType(keyField, expectedTypeName, actualTypeName));
1438 internal static ArgumentException NoCorrespondingOSpaceTypeForEnumKeyField(string argument, string keyField, string cspaceTypeName) {
1439 return Argument(System.Data.Entity.Strings.EntityKey_NoCorrespondingOSpaceTypeForEnumKeyMember(keyField, cspaceTypeName), argument);
1441 internal static InvalidOperationException NoCorrespondingOSpaceTypeForEnumKeyFieldInvalidOperation(string keyField, string cspaceTypeName) {
1442 return InvalidOperation(System.Data.Entity.Strings.EntityKey_NoCorrespondingOSpaceTypeForEnumKeyMember(keyField, cspaceTypeName));
1444 internal static ArgumentException MissingKeyValue(string argument, string keyField, string typeName) {
1445 return MissingKeyValue(argument, keyField, typeName, null);
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);
1450 internal static InvalidOperationException NullKeyValue(string keyField, string typeName)
1452 return InvalidOperation(System.Data.Entity.Strings.EntityKey_NullKeyValue(keyField, typeName));
1454 internal static InvalidOperationException MissingKeyValueInvalidOperation(string keyField, string typeName)
1456 return InvalidOperation(System.Data.Entity.Strings.EntityKey_MissingKeyValue(keyField, typeName));
1458 internal static ArgumentException NoNullsAllowedInKeyValuePairs(string argument) {
1459 return Argument(System.Data.Entity.Strings.EntityKey_NoNullsAllowedInKeyValuePairs, argument);
1461 internal static ArgumentException EntityKeyMustHaveValues(string argument) {
1462 return Argument(System.Data.Entity.Strings.EntityKey_EntityKeyMustHaveValues, argument);
1464 internal static ArgumentException InvalidQualifiedEntitySetName() {
1465 return Argument(System.Data.Entity.Strings.EntityKey_InvalidQualifiedEntitySetName, "qualifiedEntitySetName");
1467 internal static ArgumentException EntityKeyInvalidName(string invalidName) {
1468 return Argument(System.Data.Entity.Strings.EntityKey_InvalidName(invalidName));
1470 internal static InvalidOperationException MissingQualifiedEntitySetName() {
1471 return InvalidOperation(System.Data.Entity.Strings.EntityKey_MissingEntitySetName);
1473 internal static InvalidOperationException CannotChangeEntityKey() {
1474 return InvalidOperation(System.Data.Entity.Strings.EntityKey_CannotChangeKey);
1477 internal static InvalidOperationException UnexpectedNullEntityKey()
1479 return new InvalidOperationException(System.Data.Entity.Strings.EntityKey_UnexpectedNull);
1481 internal static InvalidOperationException EntityKeyDoesntMatchKeySetOnEntity(object entity)
1483 return new InvalidOperationException(System.Data.Entity.Strings.EntityKey_DoesntMatchKeyOnEntity(entity.GetType().FullName));
1485 internal static void CheckEntityKeyNull(EntityKey entityKey)
1487 if ((object)entityKey == null)
1489 throw EntityUtil.UnexpectedNullEntityKey();
1492 internal static void CheckEntityKeysMatch(IEntityWrapper wrappedEntity, EntityKey key)
1494 if (wrappedEntity.EntityKey != key)
1496 throw EntityUtil.EntityKeyDoesntMatchKeySetOnEntity(wrappedEntity.Entity);
1499 internal static InvalidOperationException UnexpectedNullRelationshipManager()
1501 return new InvalidOperationException(System.Data.Entity.Strings.RelationshipManager_UnexpectedNull);
1503 internal static InvalidOperationException InvalidRelationshipManagerOwner()
1505 return EntityUtil.InvalidOperation(System.Data.Entity.Strings.RelationshipManager_InvalidRelationshipManagerOwner);
1508 internal static void ValidateEntitySetInKey(EntityKey key, EntitySet entitySet)
1510 ValidateEntitySetInKey(key, entitySet, null);
1512 internal static void ValidateEntitySetInKey(EntityKey key, EntitySet entitySet, string argument)
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");
1518 string containerName1 = key.EntityContainerName;
1519 string setName1 = key.EntitySetName;
1520 string containerName2 = entitySet.EntityContainer.Name;
1521 string setName2 = entitySet.Name;
1523 if (!StringComparer.Ordinal.Equals(containerName1, containerName2) ||
1524 !StringComparer.Ordinal.Equals(setName1, setName2))
1526 if (String.IsNullOrEmpty(argument))
1528 throw EntityUtil.InvalidEntitySetInKey(
1529 containerName1, setName1,
1530 containerName2, setName2);
1534 throw EntityUtil.InvalidEntitySetInKeyFromName(
1535 containerName1, setName1,
1536 containerName2, setName2, argument);
1543 // IDataParameter.Direction
1544 static internal ArgumentOutOfRangeException InvalidMergeOption(MergeOption 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());
1555 return InvalidEnumerationValue(typeof(MergeOption), (int) value);
1558 static internal ArgumentOutOfRangeException InvalidRefreshMode(RefreshMode value) {
1561 case RefreshMode.ClientWins:
1562 case RefreshMode.StoreWins:
1563 Debug.Assert(false, "valid RefreshMode " + value.ToString());
1567 return InvalidEnumerationValue(typeof(RefreshMode), (int) value);
1573 static internal ArgumentException InvalidDataType(TypeCode typecode) {
1574 return Argument(System.Data.Entity.Strings.ADP_InvalidDataType(typecode.ToString()));
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));
1581 static internal ArgumentOutOfRangeException InvalidParameterDirection(ParameterDirection value)
1586 case ParameterDirection.Input:
1587 case ParameterDirection.Output:
1588 case ParameterDirection.InputOutput:
1589 case ParameterDirection.ReturnValue:
1590 Debug.Assert(false, "valid ParameterDirection " + value.ToString());
1594 return InvalidEnumerationValue(typeof(ParameterDirection), (int)value);
1596 static internal ArgumentOutOfRangeException InvalidDataRowVersion(DataRowVersion value)
1601 case DataRowVersion.Default:
1602 case DataRowVersion.Current:
1603 case DataRowVersion.Original:
1604 case DataRowVersion.Proposed:
1605 Debug.Assert(false, "valid DataRowVersion " + value.ToString());
1610 return InvalidEnumerationValue(typeof(DataRowVersion), (int)value);
1615 static private IEnumerable<ObjectStateEntry> ProcessStateEntries(IEnumerable<IEntityStateEntry> 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)
1626 static internal void ValidateNecessaryModificationFunctionMapping(
1627 StorageModificationFunctionMapping mapping, string currentState,
1628 IEntityStateEntry stateEntry, string type, string typeName)
1630 if (null == mapping)
1632 throw EntityUtil.Update(Strings.Update_MissingFunctionMapping(currentState, type, typeName),
1634 new List<IEntityStateEntry>() { stateEntry });
1637 static internal UpdateException Update(string message, Exception innerException, params IEntityStateEntry[] stateEntries) {
1638 return Update(message, innerException, (IEnumerable<IEntityStateEntry>)stateEntries);
1640 static internal UpdateException Update(string message, Exception innerException, IEnumerable<IEntityStateEntry> stateEntries)
1642 return new UpdateException(message, innerException, ProcessStateEntries(stateEntries));
1644 static internal OptimisticConcurrencyException UpdateConcurrency(long rowsAffected, Exception innerException, IEnumerable<IEntityStateEntry> stateEntries)
1646 string message = System.Data.Entity.Strings.Update_ConcurrencyError(rowsAffected);
1647 return new OptimisticConcurrencyException(message, innerException, ProcessStateEntries(stateEntries));
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))
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);
1663 // Range of acceptable values
1664 return Update(System.Data.Entity.Strings.Update_RelationshipCardinalityConstraintViolation(
1665 entitySetName, relationshipSetName, actualCountString, otherEndPluralName,
1666 minimumCountString, maximumCountString), null, stateEntry);
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);
1673 static private string ConvertCardinalityToString(int? cardinality) {
1675 if (!cardinality.HasValue) { // null indicates * (unlimited)
1679 result = cardinality.Value.ToString(CultureInfo.CurrentCulture);
1683 static internal UpdateException UpdateMissingEntity(string relationshipSetName, string entitySetName) {
1684 return Update(System.Data.Entity.Strings.Update_MissingEntity(relationshipSetName, entitySetName), null);
1687 static internal ArgumentException CollectionParameterElementIsNull(string parameterName) {
1688 return Argument(System.Data.Entity.Strings.ADP_CollectionParameterElementIsNull(parameterName));
1690 static internal ArgumentException CollectionParameterElementIsNullOrEmpty(string parameterName) {
1691 return Argument(System.Data.Entity.Strings.ADP_CollectionParameterElementIsNullOrEmpty(parameterName));
1694 static internal InvalidOperationException FunctionHasNoDefinition(EdmFunction function)
1696 return InvalidOperation(System.Data.Entity.Strings.Cqt_UDF_FunctionHasNoDefinition(function.Identity));
1699 static internal InvalidOperationException FunctionDefinitionResultTypeMismatch(EdmFunction function, TypeUsage generatedDefinitionResultType)
1701 return InvalidOperation(System.Data.Entity.Strings.Cqt_UDF_FunctionDefinitionResultTypeMismatch(
1702 TypeHelpers.GetFullName(function.ReturnParameter.TypeUsage),
1704 TypeHelpers.GetFullName(generatedDefinitionResultType)));
1707 static internal Exception EntityParameterCollectionInvalidIndex(int index, int count)
1709 return new IndexOutOfRangeException(System.Data.Entity.Strings.EntityParameterCollectionInvalidIndex(index.ToString(CultureInfo.InvariantCulture), count.ToString(CultureInfo.InvariantCulture)));
1711 static internal Exception EntityParameterCollectionInvalidParameterName(string parameterName)
1713 return new IndexOutOfRangeException(System.Data.Entity.Strings.EntityParameterCollectionInvalidParameterName(parameterName));
1715 static internal Exception EntityParameterNull(string parameter)
1717 return new ArgumentNullException(parameter, System.Data.Entity.Strings.EntityParameterNull);
1719 static internal Exception InvalidEntityParameterType(object invalidValue)
1721 return new InvalidCastException(System.Data.Entity.Strings.InvalidEntityParameterType(invalidValue.GetType().Name));
1723 static internal ArgumentException EntityParameterCollectionRemoveInvalidObject()
1725 return new ArgumentException(System.Data.Entity.Strings.EntityParameterCollectionRemoveInvalidObject);
1727 static internal ArgumentException EntityParameterContainedByAnotherCollection()
1729 return new ArgumentException(System.Data.Entity.Strings.EntityParameterContainedByAnotherCollection);
1731 ////////////////////////////////////////////////////////////////////////
1732 ////////////////////////////////////////////////////////////////////////
1733 ////////////////////////////////////////////////////////////////////////
1737 internal static void ThrowArgumentNullException(string parameterName)
1739 throw ArgumentNull(parameterName);
1741 internal static void ThrowArgumentOutOfRangeException(string parameterName)
1743 throw ArgumentOutOfRange(parameterName);
1745 internal static T CheckArgumentOutOfRange<T>(T[] values, int index, string parameterName)
1747 Debug.Assert(null != values, "null values"); // use a different method if values can be null
1748 if (unchecked((uint)values.Length <= (uint)index))
1750 ThrowArgumentOutOfRangeException(parameterName);
1752 return values[index];
1755 static internal T CheckArgumentNull<T>(T value, string parameterName) where T : class
1759 ThrowArgumentNullException(parameterName);
1764 static internal IEnumerable<T> CheckArgumentContainsNull<T>(ref IEnumerable<T> enumerableArgument, string argumentName) where T : class
1766 GetCheapestSafeEnumerableAsCollection(ref enumerableArgument);
1767 foreach (T item in enumerableArgument)
1771 throw EntityUtil.Argument(Strings.CheckArgumentContainsNullFailed(argumentName));
1774 return enumerableArgument;
1777 static internal IEnumerable<T> CheckArgumentEmpty<T>(ref IEnumerable<T> enumerableArgument, Func<string, string> errorMessage, string argumentName)
1780 GetCheapestSafeCountOfEnumerable(ref enumerableArgument, out count);
1783 throw EntityUtil.Argument(errorMessage(argumentName));
1785 return enumerableArgument;
1788 private static void GetCheapestSafeCountOfEnumerable<T>(ref IEnumerable<T> enumerable, out int count)
1790 ICollection<T> collection = GetCheapestSafeEnumerableAsCollection(ref enumerable);
1791 count = collection.Count;
1794 private static ICollection<T> GetCheapestSafeEnumerableAsCollection<T>(ref IEnumerable<T> enumerable)
1796 ICollection<T> collection = enumerable as ICollection<T>;
1797 if (collection != null)
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>;
1808 static internal T GenericCheckArgumentNull<T>(T value, string parameterName) where T: class
1810 return CheckArgumentNull(value, parameterName);
1813 // EntityConnectionStringBuilder
1814 static internal ArgumentException KeywordNotSupported(string keyword)
1816 return Argument(System.Data.Entity.Strings.EntityClient_KeywordNotSupported(keyword));
1819 static internal ArgumentException ADP_KeywordNotSupported(string keyword)
1821 return Argument(System.Data.Entity.Strings.ADP_KeywordNotSupported(keyword));
1824 // Invalid Enumeration
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);
1831 /// Given a provider factory, this returns the provider invariant name for the provider.
1833 [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
1834 internal static bool TryGetProviderInvariantName(DbProviderFactory providerFactory, out string invariantName)
1836 Debug.Assert(providerFactory != null);
1838 var connectionProviderFactoryType = providerFactory.GetType();
1839 var connectionProviderFactoryAssemblyName = new AssemblyName(
1840 connectionProviderFactoryType.Assembly.FullName);
1842 foreach (DataRow row in DbProviderFactories.GetFactoryClasses().Rows)
1844 var assemblyQualifiedTypeName = (string)row[AssemblyQualifiedNameIndex];
1846 AssemblyName rowProviderFactoryAssemblyName = null;
1848 // parse the provider factory assembly qualified type name
1850 assemblyQualifiedTypeName,
1853 rowProviderFactoryAssemblyName = a;
1857 (_, __, ___) => null);
1859 if (rowProviderFactoryAssemblyName != null)
1862 connectionProviderFactoryAssemblyName.Name,
1863 rowProviderFactoryAssemblyName.Name,
1864 StringComparison.OrdinalIgnoreCase))
1868 var foundFactory = DbProviderFactories.GetFactory(row);
1870 if (foundFactory.GetType().Equals(connectionProviderFactoryType))
1872 invariantName = (string)row[InvariantNameIndex];
1876 catch (Exception ex)
1878 Debug.Fail("GetFactory failed with: " + ex);
1879 // Ignore bad providers.
1884 invariantName = null;
1888 static internal bool AssemblyNamesMatch(string infoRowProviderAssemblyName, AssemblyName targetAssemblyName)
1890 if (string.IsNullOrWhiteSpace(infoRowProviderAssemblyName))
1895 AssemblyName assemblyName = null;
1898 assemblyName = new AssemblyName(infoRowProviderAssemblyName);
1902 // Ignore broken provider entries
1903 if (!IsCatchableExceptionType(e))
1910 Debug.Assert(assemblyName != null, "assemblyName should not be null at this point");
1912 // Match the provider assembly details
1913 if (! string.Equals(targetAssemblyName.Name, assemblyName.Name, StringComparison.OrdinalIgnoreCase))
1918 if (targetAssemblyName.Version == null || assemblyName.Version == null)
1923 if ((targetAssemblyName.Version.Major != assemblyName.Version.Major) ||
1924 (targetAssemblyName.Version.Minor != assemblyName.Version.Minor))
1929 var targetPublicKeyToken = targetAssemblyName.GetPublicKeyToken();
1930 return (targetPublicKeyToken != null)
1931 && targetPublicKeyToken.SequenceEqual(assemblyName.GetPublicKeyToken());
1934 // Invalid string argument
1935 static internal void CheckStringArgument(string value, string parameterName)
1937 // Throw ArgumentNullException when string is null
1938 CheckArgumentNull(value, parameterName);
1940 // Throw ArgumentException when string is empty
1941 if (value.Length == 0)
1943 throw InvalidStringArgument(parameterName);
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);
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();
1963 return ( (type != StackOverflowType) &&
1964 (type != OutOfMemoryType) &&
1965 (type != ThreadAbortType) &&
1966 (type != NullReferenceType) &&
1967 (type != AccessViolationType) &&
1968 !SecurityType.IsAssignableFrom(type));
1971 static internal bool IsCatchableEntityExceptionType(Exception e)
1973 Debug.Assert(e != null, "Unexpected null exception!");
1974 Type type = e.GetType();
1976 return IsCatchableExceptionType(e) &&
1977 type != CommandExecutionType &&
1978 type != CommandCompilationType &&
1982 static internal bool IsNull(object value) {
1983 if ((null == value) || (DBNull.Value == value)) {
1986 INullable nullable = (value as INullable);
1987 return ((null != nullable) && nullable.IsNull);
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.
1996 static internal void BoolExprAssert(bool condition, string message)
2000 throw InternalError(InternalErrorCode.BoolExprAssert, 0, message);
2004 static internal PropertyInfo GetTopProperty(Type t, string propertyName)
2006 return GetTopProperty(ref t, propertyName);
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.
2013 /// <param name="t"></param>
2014 /// <param name="propertyName"></param>
2015 /// <returns></returns>
2016 static internal PropertyInfo GetTopProperty(ref Type t, string propertyName)
2018 PropertyInfo propertyInfo = null;
2019 while (propertyInfo == null && t != null)
2021 propertyInfo = t.GetProperty(propertyName, BindingFlags.Instance |
2022 BindingFlags.Public |
2023 BindingFlags.NonPublic |
2024 BindingFlags.DeclaredOnly);
2027 t = propertyInfo.DeclaringType;
2028 return propertyInfo;
2031 static internal int SrcCompare(string strA, string strB)
2033 return ((strA == strB) ? 0 : 1);
2035 static internal int DstCompare(string strA, string strB)
2037 return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, EntityUtil.StringCompareOptions);
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.
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)
2048 return Path.GetFullPath(filename);
2051 public static T FieldCast<T>(object value) {
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);
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;
2064 public static Type[] GetTypesSpecial(Assembly assembly)
2066 return ReferenceEquals(assembly, typeof(ObjectContext).Assembly)
2068 : assembly.GetTypes();
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.
2076 static bool? useFx40CompatMode;
2077 static public bool UseFx40CompatMode
2081 if (!useFx40CompatMode.HasValue)
2083 string fxname = AppDomain.CurrentDomain.SetupInformation.TargetFrameworkName;
2085 if (string.IsNullOrWhiteSpace(fxname))
2087 Assembly entryAssembly = Assembly.GetEntryAssembly(); // entry assembly can be unmanaged.
2089 if (entryAssembly != null)
2091 TargetFrameworkAttribute fxAttrib = entryAssembly.GetCustomAttribute<TargetFrameworkAttribute>();
2092 if (fxAttrib != null)
2094 fxname = fxAttrib.FrameworkName;
2099 if (!string.IsNullOrWhiteSpace(fxname))
2103 FrameworkName compiledFxName = new FrameworkName(fxname);
2104 Version fxv45 = new Version(4, 5);
2106 useFx40CompatMode = compiledFxName.Version < fxv45;
2108 catch (System.ArgumentException)
2113 if (!useFx40CompatMode.HasValue)
2115 useFx40CompatMode = true;
2119 return useFx40CompatMode.Value;