private IEnumerable <DbModificationCommandTree> Generate(string entityIdentity, EntityState state) { DebugCheck.NotEmpty(entityIdentity); var entityType = _metadataWorkspace .GetItem <EntityType>(entityIdentity, DataSpace.CSpace); using (var context = CreateContext()) { var entity = InstantiateAndAttachEntity(entityType, context); if (state != EntityState.Deleted) { // For deletes, we need to set the state // _after_ dealing with IAs. context.Entry(entity).State = state; } ChangeRelationshipStates(context, entityType, entity, state); if (state == EntityState.Deleted) { context.Entry(entity).State = state; } HandleTableSplitting(context, entityType, entity, state); using (var commandTracer = new CommandTracer(context)) { ((IObjectContextAdapter)context).ObjectContext.SaveChanges(SaveOptions.None); foreach (var commandTree in commandTracer.CommandTrees) { yield return((DbModificationCommandTree)commandTree); } } } }
internal void LogError(string statusMessage, Exception exception) { DebugCheck.NotEmpty(statusMessage); DebugCheck.NotNull(exception); var edmSchemaErrorException = exception as EdmSchemaErrorException; var compilerErrorException = exception as CompilerErrorException; _dte2.StatusBar.Text = statusMessage; var buildOutputWindow = _dte2.ToolWindows.OutputWindow.OutputWindowPanes.Item("Build"); buildOutputWindow.OutputString(Environment.NewLine); if (edmSchemaErrorException != null) { buildOutputWindow.OutputString(edmSchemaErrorException.Message + Environment.NewLine); foreach (var error in edmSchemaErrorException.Errors) { buildOutputWindow.OutputString(error + Environment.NewLine); } } else if (compilerErrorException != null) { buildOutputWindow.OutputString(compilerErrorException.Message + Environment.NewLine); foreach (var error in compilerErrorException.Errors) { buildOutputWindow.OutputString(error + Environment.NewLine); } } else { buildOutputWindow.OutputString(exception + Environment.NewLine); } buildOutputWindow.Activate(); }
// virtual for testing internal virtual void WriteSchemaElementHeader(string schemaNamespace) { DebugCheck.NotEmpty(schemaNamespace); var xmlNamespace = XmlConstants.GetCsdlNamespace(_version); _xmlWriter.WriteStartElement(XmlConstants.Schema, xmlNamespace); _xmlWriter.WriteAttributeString(XmlConstants.Namespace, schemaNamespace); _xmlWriter.WriteAttributeString(XmlConstants.Alias, XmlConstants.Self); if (_version == XmlConstants.EdmVersionForV3) { _xmlWriter.WriteAttributeString( AnnotationNamespacePrefix, XmlConstants.UseStrongSpatialTypes, XmlConstants.AnnotationNamespace, XmlConstants.False); } _xmlWriter.WriteAttributeString("xmlns", AnnotationNamespacePrefix, null, XmlConstants.AnnotationNamespace); _xmlWriter.WriteAttributeString("xmlns", CustomAnnotationNamespacePrefix, null, XmlConstants.CustomAnnotationNamespace); }
public static DatabaseName Parse(string name) { DebugCheck.NotEmpty(name); var parts = name.Trim().Split('.'); Debug.Assert(parts.Length > 0); if (parts.Length > 2) { throw Error.InvalidDatabaseName(name); } string schema = null; string objectName; if (parts.Length == 2) { schema = parts[0]; if (string.IsNullOrWhiteSpace(schema)) { throw Error.InvalidDatabaseName(name); } objectName = parts[1]; } else { objectName = parts[0]; } if (string.IsNullOrWhiteSpace(objectName)) { throw Error.InvalidDatabaseName(name); } return(new DatabaseName(objectName, schema)); }
// <summary> // Gets an internal object representing a navigation, scalar, or complex property. // This method is virtual to allow mocking. // </summary> // <param name="propertyName"> Name of the property. </param> // <param name="requestedType"> The type of entity requested, which may be 'object' if any type can be accepted. </param> // <returns> The entry. </returns> public virtual InternalMemberEntry Member(string propertyName, Type requestedType = null) { DebugCheck.NotEmpty(propertyName); requestedType = requestedType ?? typeof(object); var properties = SplitName(propertyName); if (properties.Count > 1) { return(Property(null, propertyName, properties, requestedType, requireComplex: false)); } var memberMetadata = GetNavigationMetadata(propertyName) ?? (MemberEntryMetadata) ValidateAndGetPropertyMetadata(propertyName, EntityType, requestedType); if (memberMetadata == null) { throw Error.DbEntityEntry_NotAProperty(propertyName, EntityType.Name); } // This check is used for non-collection entries. For collection entries there is a more specific // check in the DbCollectionEntry class. // Examples: // If (!SomeStringProp is Object) => okay // If (!SomeFeaturedProduct is Product) => okay // If (!SomeProduct is FeaturedProduct) => throw if (memberMetadata.MemberEntryType != MemberEntryType.CollectionNavigationProperty && !requestedType.IsAssignableFrom(memberMetadata.MemberType)) { throw Error.DbEntityEntry_WrongGenericForNavProp( propertyName, EntityType.Name, requestedType.Name, memberMetadata.MemberType.Name); } return(memberMetadata.CreateMemberEntry(this, null)); }
public HistoryRepository( string connectionString, DbProviderFactory providerFactory, string contextKey, int?commandTimeout, IEnumerable <string> schemas = null, HistoryContextFactory historyContextFactory = null) : base(connectionString, providerFactory) { DebugCheck.NotEmpty(contextKey); _contextKey = contextKey; _commandTimeout = commandTimeout; _schemas = new[] { EdmModelExtensions.DefaultSchema } .Concat(schemas ?? Enumerable.Empty <string>()) .Distinct(); _historyContextFactory = historyContextFactory ?? DbConfiguration.GetService <HistoryContextFactory>(); }
internal virtual string GetProviderServicesInternal(string invariantName) { DebugCheck.NotEmpty(invariantName); DbConfiguration.LoadConfiguration(_assembly); var dependencyResolver = DbConfiguration.DependencyResolver; DbProviderServices providerServices = null; try { providerServices = dependencyResolver.GetService <DbProviderServices>(invariantName); } catch { } if (providerServices == null) { return(null); } return(providerServices.GetType().AssemblyQualifiedName); }
/// <summary> /// Gets or sets the value of the property with the specified property name. /// The value may be a nested instance of this class. /// </summary> /// <param name="propertyName"> The property name. </param> /// <value> The value of the property. </value> public object this[string propertyName] { get { DebugCheck.NotEmpty(propertyName); return(GetItem(propertyName).Value); } set { DebugCheck.NotEmpty(propertyName); var asPropertyValues = value as DbPropertyValues; if (asPropertyValues != null) { value = asPropertyValues.InternalPropertyValues; } var item = GetItem(propertyName); var nestedValues = item.Value as InternalPropertyValues; if (nestedValues == null) { // Not a nested dictionary, so just set the value directly. SetValue(item, value); } else { // Check that the value passed is an InternalPropertyValues and not null var valueAsValues = value as InternalPropertyValues; if (valueAsValues == null) { throw Error.DbPropertyValues_AttemptToSetNonValuesOnComplexProperty(); } nestedValues.SetValues(valueAsValues); } } }
internal AssociationSet FindCSpaceAssociationSet(AssociationType associationType, string endName, EntitySet endEntitySet) { DebugCheck.NotNull(associationType); DebugCheck.NotEmpty(endName); DebugCheck.NotNull(endEntitySet); Debug.Assert(associationType.DataSpace == DataSpace.CSpace); var array = GetCSpaceAssociationTypeToSetsMap(); var index = associationType.Index; var objectAtIndex = array[index]; if (objectAtIndex == null) { return(null); } var associationSet = objectAtIndex as AssociationSet; if (associationSet != null) { return(associationSet.AssociationSetEnds[endName].EntitySet == endEntitySet ? associationSet : null); } var items = (AssociationSet[])objectAtIndex; for (var i = 0; i < items.Length; i++) { associationSet = items[i]; if (associationSet.AssociationSetEnds[endName].EntitySet == endEntitySet) { return(associationSet); } } return(null); }
public void Add(string columnName, IndexAttribute index) { DebugCheck.NotEmpty(columnName); DebugCheck.NotNull(index); Debug.Assert(_index.Name == index.Name); if (_columns.ContainsKey(index.Order)) { throw new InvalidOperationException( Strings.OrderConflictWhenConsolidating(index.Name, _table, index.Order, _columns[index.Order], columnName)); } _columns[index.Order] = columnName; var compat = _index.IsCompatibleWith(index, ignoreOrder: true); if (!compat) { throw new InvalidOperationException(Strings.ConflictWhenConsolidating(index.Name, _table, compat.ErrorMessage)); } _index = _index.MergeWith(index, ignoreOrder: true); }
internal static ObjectQueryState GroupBy( ObjectQueryState query, string alias, string keys, string projection, ObjectParameter[] parameters) { DebugCheck.NotEmpty(alias); DebugCheck.NotEmpty(keys); DebugCheck.NotEmpty(projection); var queryText = GetCommandText(query); // Build the new query string: // "SELECT <projection> FROM (<this query>) AS <alias> GROUP BY <keys>" var queryLength = _selectOp.Length + projection.Length + _fromOp.Length + queryText.Length + _asOp.Length + alias.Length + _groupByOp.Length + keys.Length; var builder = new StringBuilder(queryLength); builder.Append(_selectOp); builder.Append(projection); builder.Append(_fromOp); builder.Append(queryText); builder.Append(_asOp); builder.Append(alias); builder.Append(_groupByOp); builder.Append(keys); // Create a new EntitySqlQueryImplementation that uses the new query as its command text. // Span should not be carried over from a GroupBy operation. return(NewBuilderQuery( query, typeof(DbDataRecord), builder, null, MergeParameters(query.ObjectContext, query.Parameters, parameters))); }
internal static bool ValidateDottedName(Schema schema, XmlReader reader, string name) { DebugCheck.NotNull(schema); DebugCheck.NotNull(reader); DebugCheck.NotEmpty(name); Debug.Assert( reader.SchemaInfo.Validity != XmlSchemaValidity.Invalid, "This method should not be called when the schema is invalid"); if (schema.DataModel == SchemaDataModelOption.EntityDataModel) { // each part of the dotted name needs to be a valid name foreach (var namePart in name.Split('.')) { if (!namePart.IsValidUndottedName()) { schema.AddError( ErrorCode.InvalidName, EdmSchemaErrorSeverity.Error, reader, Strings.InvalidName(name, reader.Name)); return(false); } } } return(true); }
public virtual MigrationOperation CreateDeleteOperation(string migrationId) { DebugCheck.NotEmpty(migrationId); using (var context = CreateContext()) { var historyRow = new HistoryRow { MigrationId = migrationId, ContextKey = _contextKey }; context.History.Attach(historyRow); context.History.Remove(historyRow); using (var commandTracer = new CommandTracer()) { context.SaveChanges(); return(new HistoryOperation(commandTracer.Commands)); } } }
public virtual XDocument GetModel(string migrationId) { DebugCheck.NotEmpty(migrationId); if (!Exists()) { return(null); } migrationId = migrationId.RestrictTo(_migrationIdMaxLength); using (var connection = CreateConnection()) { using (var context = CreateContext(connection)) { var model = CreateHistoryQuery(context) .Where(h => h.MigrationId == migrationId) .Select(h => h.Model) .Single(); return((model == null) ? null : new ModelCompressor().Decompress(model)); } } }
public virtual MigrationOperation CreateInsertOperation(string migrationId, XDocument model) { DebugCheck.NotEmpty(migrationId); DebugCheck.NotNull(model); DbConnection connection = null; try { connection = CreateConnection(); using (var context = CreateContext(connection)) { context.History.Add( new HistoryRow { MigrationId = migrationId.RestrictTo(_migrationIdMaxLength), ContextKey = _contextKey, Model = new ModelCompressor().Compress(model), ProductVersion = _productVersion }); using (var commandTracer = new CommandTracer(context)) { context.SaveChanges(); return(new HistoryOperation( commandTracer.CommandTrees.OfType <DbModificationCommandTree>().ToList())); } } } finally { DisposeConnection(connection); } }
public virtual MigrationOperation CreateDeleteOperation(string migrationId) { DebugCheck.NotEmpty(migrationId); DbConnection connection = null; try { connection = CreateConnection(); using (var context = CreateContext(connection)) { var historyRow = new HistoryRow { MigrationId = migrationId.RestrictTo(_migrationIdMaxLength), ContextKey = _contextKey }; context.History.Attach(historyRow); context.History.Remove(historyRow); using (var commandTracer = new CommandTracer(context)) { context.SaveChanges(); return(new HistoryOperation( commandTracer.CommandTrees.OfType <DbModificationCommandTree>().ToList())); } } } finally { DisposeConnection(connection); } }
public object Deserialize(string name, string value) { DebugCheck.NotEmpty(name); DebugCheck.NotNull(value); // We avoid throwing here if the type could not be loaded because we might be loading an // old EDMX from, for example, the MigrationHistory table, and the CLR type might no longer exist. // Note that the exceptions caught below can be thrown even when "throwOnError" is false. try { return(Type.GetType(value, throwOnError: false)); } catch (FileLoadException) { } catch (TargetInvocationException) { } catch (BadImageFormatException) { } return(null); }
public virtual IEnumerable <string> GetMigrationsSince(string migrationId) { DebugCheck.NotEmpty(migrationId); var exists = Exists(); using (var connection = CreateConnection()) { using (var context = CreateContext(connection)) { var query = CreateHistoryQuery(context); migrationId = migrationId.RestrictTo(_migrationIdMaxLength); if (migrationId != DbMigrator.InitialDatabase) { if (!exists || !query.Any(h => h.MigrationId == migrationId)) { throw Error.MigrationNotFound(migrationId); } query = query.Where(h => string.Compare(h.MigrationId, migrationId, StringComparison.Ordinal) > 0); } else if (!exists) { return(Enumerable.Empty <string>()); } return(query .OrderByDescending(h => h.MigrationId) .Select(h => h.MigrationId) .ToList()); } } }
public virtual MigrationOperation CreateInsertOperation(string migrationId, XDocument model) { DebugCheck.NotEmpty(migrationId); DebugCheck.NotNull(model); using (var context = CreateContext()) { context.History.Add( new HistoryRow { MigrationId = migrationId, ContextKey = _contextKey, Model = new ModelCompressor().Compress(model), ProductVersion = _productVersion }); using (var commandTracer = new CommandTracer()) { context.SaveChanges(); return(new HistoryOperation(commandTracer.Commands)); } } }
public virtual DbProviderServices GetInstanceByConvention(string providerInvariantName) { DebugCheck.NotEmpty(providerInvariantName); var providerTemplate = providerInvariantName.Equals("System.Data.SqlClient", StringComparison.OrdinalIgnoreCase) ? "System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer, Version={0}{1}" : providerInvariantName.Equals("System.Data.SqlServerCe.4.0", StringComparison.OrdinalIgnoreCase) ? "System.Data.Entity.SqlServerCompact.SqlCeProviderServices, EntityFramework.SqlServerCompact, Version={0}{1}" : null; if (providerTemplate == null) { throw new InvalidOperationException(Strings.EF6Providers_NoProviderFound(providerInvariantName)); } return(GetInstance( string.Format( CultureInfo.InvariantCulture, providerTemplate, new AssemblyName(typeof(DbContext).Assembly.FullName).Version, ", Culture=neutral, PublicKeyToken=b77a5c561934e089"), providerInvariantName)); }
public void SetPropertyAttributes(string propertyName, params Attribute[] attributes) { DebugCheck.NotEmpty(propertyName); PropertyAttributes[propertyName] = attributes; }
public HistoryRepository( InternalContext usersContext, string connectionString, DbProviderFactory providerFactory, string contextKey, int?commandTimeout, Func <DbConnection, string, HistoryContext> historyContextFactory, IEnumerable <string> schemas = null, DbContext contextForInterception = null, DatabaseExistenceState initialExistence = DatabaseExistenceState.Unknown) : base(usersContext, connectionString, providerFactory) { DebugCheck.NotEmpty(contextKey); DebugCheck.NotNull(historyContextFactory); _initialExistence = initialExistence; _commandTimeout = commandTimeout; _existingTransaction = usersContext.TryGetCurrentStoreTransaction(); _schemas = new[] { EdmModelExtensions.DefaultSchema } .Concat(schemas ?? Enumerable.Empty <string>()) .Distinct(); _contextForInterception = contextForInterception; _historyContextFactory = historyContextFactory; DbConnection connection = null; try { connection = CreateConnection(); using (var context = CreateContext(connection)) { var historyRowEntity = ((IObjectContextAdapter)context).ObjectContext .MetadataWorkspace .GetItems <EntityType>(DataSpace.CSpace) .Single(et => et.GetClrType() == typeof(HistoryRow)); var maxLength = historyRowEntity .Properties .Single(p => p.GetClrPropertyInfo().IsSameAs(MigrationIdProperty)) .MaxLength; _migrationIdMaxLength = maxLength.HasValue ? maxLength.Value : HistoryContext.MigrationIdMaxLength; maxLength = historyRowEntity .Properties .Single(p => p.GetClrPropertyInfo().IsSameAs(ContextKeyProperty)) .MaxLength; _contextKeyMaxLength = maxLength.HasValue ? maxLength.Value : HistoryContext.ContextKeyMaxLength; } } finally { DisposeConnection(connection); } _contextKey = contextKey.RestrictTo(_contextKeyMaxLength); }
public void RowsAffectedParameter(string name) { DebugCheck.NotEmpty(name); _rowsAffectedParameter = name; }
// <summary> // Determines if this collection contains an item of the given identity // </summary> // <param name="identity"> The identity of the item to check for </param> // <returns> True if the collection contains the item with the given identity </returns> // <exception cref="System.ArgumentNullException">Thrown if identity argument passed in is null</exception> // <exception cref="System.ArgumentException">Thrown if identity argument passed in is empty string</exception> public virtual bool ContainsIdentity(string identity) { DebugCheck.NotEmpty(identity); return(ContainsIdentityCaseSensitive(identity)); }
//For CreateCompositeFromFilePaths method call. But the path is not created in this method. public static MetadataArtifactLoader CreateCompositeFromFilePaths(IEnumerable <string> filePaths, string validExtension) { DebugCheck.NotEmpty(validExtension); return(CreateCompositeFromFilePaths(filePaths, validExtension, new DefaultAssemblyResolver())); }
public static string CreateMigrationId(string migrationName) { DebugCheck.NotEmpty(migrationName); return(UtcNowGenerator.UtcNowAsMigrationIdTimestamp() + "_" + migrationName); }
// <summary> // Initializes a new instance of the <see cref="ModelContainerConvention" /> class. // </summary> // <param name="containerName"> The model container name. </param> internal ModelContainerConvention(string containerName) { DebugCheck.NotEmpty(containerName); _containerName = containerName; }
internal MetadataMember ResolveUnqualifiedName(string name, bool partOfQualifiedName, ErrorContext errCtx) { DebugCheck.NotEmpty(name); // // In the case of Name1.Name2...NameN and if backward compatibility mode is on, then resolve Name1 as namespace only, ignore any other possible resolutions. // var resolveAsNamespaceOnly = partOfQualifiedName && _resolveLeftMostUnqualifiedNameAsNamespaceOnly; // // In the case of Name1.Name2...NameN, ignore functions while resolving Name1: functions don't have members. // var includeFunctions = !partOfQualifiedName; // // Try resolving as an inline function. // InlineFunctionGroup inlineFunctionGroup; if (!resolveAsNamespaceOnly && includeFunctions && TryGetInlineFunction(name, out inlineFunctionGroup)) { return(inlineFunctionGroup); } // // Try resolving as a namespace alias. // MetadataNamespace aliasedNamespaceImport; if (_aliasedNamespaces.TryGetValue(name, out aliasedNamespaceImport)) { return(aliasedNamespaceImport); } if (!resolveAsNamespaceOnly) { // // Try resolving as a type or functionGroup in the global namespace or as an imported member. // Throw if ambiguous. // MetadataType type = null; MetadataFunctionGroup functionGroup = null; if (!TryGetTypeFromMetadata(name, out type)) { if (includeFunctions) { // // If name looks like a multipart identifier, try resolving it in the global namespace. // Escaped multipart identifiers usually appear in views: select [NS1.NS2.Product](...) from ... // var multipart = name.Split('.'); if (multipart.Length > 1 && multipart.All(p => p.Length > 0)) { var functionName = multipart[multipart.Length - 1]; var namespaceName = name.Substring(0, name.Length - functionName.Length - 1); TryGetFunctionFromMetadata(namespaceName, functionName, out functionGroup); } } } // // Try resolving as an imported member. // MetadataNamespace importedMemberNamespace = null; foreach (var namespaceImport in _namespaces) { var fullName = GetFullName(namespaceImport.Name, name); MetadataType importedType; if (TryGetTypeFromMetadata(fullName, out importedType)) { if (type == null && functionGroup == null) { type = importedType; importedMemberNamespace = namespaceImport; } else { throw AmbiguousMetadataMemberName(errCtx, name, namespaceImport, importedMemberNamespace); } } MetadataFunctionGroup importedFunctionGroup; if (includeFunctions && TryGetFunctionFromMetadata(namespaceImport.Name, name, out importedFunctionGroup)) { if (type == null && functionGroup == null) { functionGroup = importedFunctionGroup; importedMemberNamespace = namespaceImport; } else { throw AmbiguousMetadataMemberName(errCtx, name, namespaceImport, importedMemberNamespace); } } } if (type != null) { return(type); } if (functionGroup != null) { return(functionGroup); } } // // Otherwise, resolve as a namespace. // return(new MetadataNamespace(name)); }
private void OptimizeContextCore( LanguageOption languageOption, string baseFileName, SelectedItem selectedItem, Action <string> generateAction) { DebugCheck.NotEmpty(baseFileName); var progressTimer = new Timer { Interval = 1000 }; try { var selectedItemPath = (string)selectedItem.ProjectItem.Properties.Item("FullPath").Value; var viewsFileName = baseFileName + ".Views" + ((languageOption == LanguageOption.GenerateCSharpCode) ? FileExtensions.CSharp : FileExtensions.VisualBasic); var viewsPath = Path.Combine( Path.GetDirectoryName(selectedItemPath), viewsFileName); _package.DTE2.SourceControl.CheckOutItemIfNeeded(viewsPath); var progress = 1; progressTimer.Tick += (sender, e) => { _package.DTE2.StatusBar.Progress(true, string.Empty, progress, 100); progress = progress == 100 ? 1 : progress + 1; _package.DTE2.StatusBar.Text = Strings.Optimize_Begin(baseFileName); }; progressTimer.Start(); Task.Factory.StartNew( () => { generateAction(viewsPath); }) .ContinueWith( t => { progressTimer.Stop(); _package.DTE2.StatusBar.Progress(false); if (t.IsFaulted) { _package.LogError(Strings.Optimize_Error(baseFileName), t.Exception); return; } selectedItem.ProjectItem.ContainingProject.ProjectItems.AddFromFile(viewsPath); _package.DTE2.ItemOperations.OpenFile(viewsPath); _package.DTE2.StatusBar.Text = Strings.Optimize_End(baseFileName, Path.GetFileName(viewsPath)); }, TaskScheduler.FromCurrentSynchronizationContext()); } catch { progressTimer.Stop(); _package.DTE2.StatusBar.Progress(false); throw; } }
public ProviderInvariantName(string name) { DebugCheck.NotEmpty(name); Name = name; }