public IConfiguration Discover(EdmProperty property, DbModel model) { Debug.Assert(property != null, "property is null."); Debug.Assert(model != null, "model is null."); var columnProperty = model.GetColumn(property); if (property.IsKey() && _identityKeyTypes.Contains(property.PrimitiveType.PrimitiveTypeKind)) { if (columnProperty.IsStoreGeneratedIdentity) { // By convention return null; } } else if (columnProperty.IsTimestamp()) { // By convention return null; } else if (columnProperty.StoreGeneratedPattern == StoreGeneratedPattern.None) { // Doesn't apply return null; } return new DatabaseGeneratedConfiguration { StoreGeneratedPattern = columnProperty.StoreGeneratedPattern }; }
/// <summary> /// Writes the Entity Data Model represented by the given <see cref="DbModel" /> to the /// given writer in EDMX form. /// </summary> /// <param name="model"> An object representing the EDM. </param> /// <param name="writer"> The writer. </param> public static void WriteEdmx(DbModel model, XmlWriter writer) { Check.NotNull(model, "model"); Check.NotNull(writer, "writer"); new EdmxSerializer().Serialize(model.DatabaseMapping, writer); }
public IConfiguration Discover(EdmProperty property, DbModel model) { Debug.Assert(property != null, "property is null."); Debug.Assert(model != null, "model is null."); if (!_precisionTypes.Contains(property.PrimitiveType.PrimitiveTypeKind)) { // Doesn't apply return null; } var storeProperty = model.GetColumn(property); var defaultPrecision = (byte)storeProperty.PrimitiveType.FacetDescriptions .First(d => d.FacetName == DbProviderManifest.PrecisionFacetName).DefaultValue; // NOTE: This facet is not propagated to the conceptual side of the reverse // engineered model. var precision = storeProperty.Precision ?? defaultPrecision; if (precision == defaultPrecision) { // By convention return null; } return new PrecisionDateTimeConfiguration { Precision = precision }; }
public override IConfiguration Discover(EdmProperty property, DbModel model) { Debug.Assert(property != null, "property is null."); Debug.Assert(model != null, "model is null."); if (!_lengthTypes.Contains(property.PrimitiveType.PrimitiveTypeKind)) { // Doesn't apply return null; } if (property.IsMaxLength || !property.MaxLength.HasValue || (property.MaxLength.Value == 128 && property.IsKey())) { // By convention return null; } var configuration = property.PrimitiveType.PrimitiveTypeKind == PrimitiveTypeKind.String ? new MaxLengthStringConfiguration() : new MaxLengthConfiguration(); configuration.MaxLength = property.MaxLength.Value; return configuration; }
static FooContext() { var modelBuilder = new ModelBuilder(); modelBuilder.DiscoverEntitiesFromContext(typeof(FooContext)); modelBuilder.Entity<Foo>().HasKey(x => x.Identifier); model = modelBuilder.CreateModel(); }
public Database Get() { if (_database == null) { DbConnection connection = _providerFactory.CreateConnection(); if (connection != null) { connection.ConnectionString = _connectionString; if (_model == null) { lock (_syncObject) { if (_model == null) { _model = CreateDbModel(connection); } } } _database = _model.CreateObjectContext<Database>(connection); } return _database; } return _database; }
/// <summary> /// Writes the Entity Data Model represented by the given <see cref = "DbModel" /> to the /// given writer in EDMX form. /// </summary> /// <param name = "modelaseMapping">An object representing the EDM.</param> /// <param name = "writer">The writer.</param> public static void WriteEdmx(DbModel model, XmlWriter writer) { //Contract.Requires(model != null); //Contract.Requires(writer != null); new EdmxSerializer().Serialize( model.DatabaseMapping, model.DatabaseMapping.Database.GetProviderInfo(), writer); }
public FunctionDiscovery(DbModel model, Type type) { Debug.Assert(model != null, "model is null"); Debug.Assert(type != null, "type is null"); _model = model; _type = type; }
public StoreFunctionBuilder(DbModel model, string schema, string @namespace = null) { Debug.Assert(model != null, "model is null"); _model = model; _schema = schema; // CodeFirstDatabaseSchema is what EF CodeFirst model builder uses for store model _namespace = @namespace ?? "CodeFirstDatabaseSchema"; }
public virtual void GenerateModel(ModelBuilderSettings settings, IVsUtils vsUtils = null, ModelBuilderEngineHostContext hostContext = null) { if (settings.GenerationOption == ModelGenerationOption.GenerateFromDatabase && String.IsNullOrEmpty(settings.DesignTimeConnectionString)) { throw new ArgumentOutOfRangeException(Resources.Engine_EmptyConnStringErrorMsg); } var generatingModelWatch = Stopwatch.StartNew(); hostContext = hostContext ?? new VSModelBuilderEngineHostContext(settings); vsUtils = vsUtils ?? new VsUtilsWrapper(); // Clear out the ModelGenErrorCache before ModelGen begins PackageManager.Package.ModelGenErrorCache.RemoveErrors(settings.ModelPath); var errors = new List<EdmSchemaError>(); try { var storeModelNamespace = GetStoreNamespace(settings); Model = GenerateModels(storeModelNamespace, settings, errors); ProcessModel(Model, storeModelNamespace, settings, hostContext, errors); hostContext.LogMessage( FormatMessage( errors.Any() ? Resources.Engine_ModelGenErrors : Resources.Engine_ModelGenSuccess, Path.GetFileName(settings.ModelPath))); if (errors.Any()) { PackageManager.Package.ModelGenErrorCache.AddErrors(settings.ModelPath, errors); } } catch (Exception e) { hostContext.LogMessage(FormatMessage(Resources.Engine_ModelGenException, e)); // The exception we re-throw will get swallowed in the message pump and therefore we need to show the message box here. // It will also prevent the form.WizardFinished from being set to true which will cause cancelling the wizard and // therefore block adding new project items to the project as well as ModelObjectItemWizardFrom.RunFinished method. vsUtils.ShowErrorDialog(FormatMessage(Resources.Engine_ModelGenExceptionMessageBox, e.GetType().Name, e.Message)); throw; } finally { generatingModelWatch.Stop(); hostContext.LogMessage(FormatMessage(Resources.LoadingDBMetadataTimeMsg, settings.LoadingDBMetatdataTime)); hostContext.LogMessage(FormatMessage(Resources.GeneratingModelTimeMsg, generatingModelWatch.Elapsed)); } }
public void Can_retrieve_entity_container_mapping() { var model = new DbModel(new EdmModel(DataSpace.CSpace), new EdmModel(DataSpace.SSpace)); var containerMapping = new EntityContainerMapping(); Assert.Null(model.ConceptualToStoreMapping); model.DatabaseMapping.AddEntityContainerMapping(containerMapping); Assert.Same(containerMapping, model.ConceptualToStoreMapping); }
public string Generate(EntitySet entitySet, DbModel model, string codeNamespace) { Debug.Assert(entitySet != null, "entitySet is null."); Debug.Assert(model != null, "model is null."); _host.Session = _host.CreateSession(); _host.Session.Add("EntitySet", entitySet); _host.Session.Add("Model", model); _host.Session.Add("Namespace", codeNamespace); return ProcessTemplate(); }
public IConfiguration Discover(EdmProperty property, DbModel model) { Debug.Assert(property != null, "property is null."); Debug.Assert(model != null, "model is null."); if (!model.GetColumn(property).IsTimestamp()) { // Doesn't apply return null; } return new TimestampConfiguration(); }
public static DbModel Model(SqlConnection con) { if ((_builder == null) || (_model == null)) { _builder = new ModelBuilder(); _builder.Configurations.Add(new AuthorConfiguration()); _builder.Configurations.Add(new TitlesConfiguration()); _builder.Configurations.Add(new PublisherConfiguration()); var edm=_builder.Build(con); _model = new DbModel(edm); } return _model; ; }
public void UpdateEdmxFromModel_updates_csdl_ssdl_msl() { var inputXml = XDocument.Parse("<root />"); var databaseMapping = new DbDatabaseMapping { Model = new EdmModel(DataSpace.CSpace), Database = new EdmModel(DataSpace.SSpace) }; var model = new DbModel(databaseMapping, new DbModelBuilder()); var mockEdmxHelper = new Mock<EdmxHelper>(inputXml); mockEdmxHelper.Setup( h => h.UpdateStorageModels( It.Is<EdmModel>(m => m == databaseMapping.Database), It.Is<string>(n => n == "storeNamespace"), It.Is<DbProviderInfo>(i => i == model.ProviderInfo), It.IsAny<List<EdmSchemaError>>())) .Returns(true); mockEdmxHelper.Setup( h => h.UpdateConceptualModels( It.Is<EdmModel>(m => m == databaseMapping.Model), It.Is<string>(n => n == "entityModelNamespace"))) .Returns(true); mockEdmxHelper.Setup( h => h.UpdateMapping( It.Is<DbModel>(m => m == model))) .Returns(true); mockEdmxHelper.Object.UpdateEdmxFromModel( model, "storeNamespace", "entityModelNamespace", new List<EdmSchemaError>()); mockEdmxHelper .Verify( h => h.UpdateStorageModels( It.Is<EdmModel>(m => m == databaseMapping.Database), It.Is<string>(n => n == "storeNamespace"), It.Is<DbProviderInfo>(i => i == model.ProviderInfo), It.IsAny<List<EdmSchemaError>>()), Times.Once()); mockEdmxHelper .Verify( h => h.UpdateConceptualModels( It.Is<EdmModel>(m => m == databaseMapping.Model), It.Is<string>(n => n == "entityModelNamespace")), Times.Once()); mockEdmxHelper .Verify( h => h.UpdateMapping( It.Is<DbModel>(m => m == model)), Times.Once()); }
// internal virtual to allow mocking protected override void ProcessModel(DbModel model, string storeModelNamespace, ModelBuilderSettings settings, ModelBuilderEngineHostContext hostContext, List<EdmSchemaError> errors) { Edmx = XDocument.Parse(_initialModelContentsFactory.GetInitialModelContents(settings.TargetSchemaVersion)); var edmxHelper = new EdmxHelper(Edmx); edmxHelper.UpdateEdmxFromModel(model, storeModelNamespace, settings.ModelNamespace, errors); // load extensions that want to update model after the wizard has run. hostContext.DispatchToModelGenerationExtensions(); UpdateDesignerInfo(edmxHelper, settings); }
public string Generate(DbModel model, string codeNamespace, string contextClassName, string connectionStringName) { Debug.Assert(model != null, "model is null."); Debug.Assert(!string.IsNullOrWhiteSpace(codeNamespace), "invalid namespace"); Debug.Assert(!string.IsNullOrWhiteSpace(contextClassName), "contextClassName"); Debug.Assert(!string.IsNullOrWhiteSpace(connectionStringName), "connectionStringName"); _host.Session = _host.CreateSession(); _host.Session.Add("Model", model); _host.Session.Add("Namespace", codeNamespace); _host.Session.Add("ContextClassName", contextClassName); _host.Session.Add("ConnectionStringName", connectionStringName); return ProcessTemplate(); }
public string Generate(EntitySet entitySet, DbModel model, string codeNamespace) { Debug.Assert(entitySet != null, "entitySet is null."); Debug.Assert(model != null, "model is null."); Session = new Dictionary<string, object> { { "EntitySet", entitySet }, { "Model", model }, { "Namespace", codeNamespace } }; Initialize(); return TransformText(); }
// virtual for testing public virtual IEnumerable<KeyValuePair<string, string>> Generate(DbModel model, string codeNamespace, string contextClassName, string connectionStringName) { var extension = _language == LangEnum.VisualBasic ? FileExtensions.VbExt : FileExtensions.CsExt; var contextFileName = contextClassName + extension; string contextFileContents; try { contextFileContents = _codeGeneratorFactory .GetContextGenerator(_language, isEmptyModel: model == null) .Generate(model, codeNamespace, contextClassName, connectionStringName); } catch (Exception ex) { throw new CodeFirstModelGenerationException( string.Format(Resources.ErrorGeneratingCodeFirstModel, contextFileName), ex); } yield return new KeyValuePair<string, string>(contextFileName, contextFileContents); if (model != null) { foreach (var entitySet in model.ConceptualModel.Container.EntitySets) { var entityTypeGenerator = _codeGeneratorFactory.GetEntityTypeGenerator(_language); var entityTypeFileName = entitySet.ElementType.Name + extension; string entityTypeFileContents; try { entityTypeFileContents = entityTypeGenerator.Generate(entitySet, model, codeNamespace); } catch (Exception ex) { throw new CodeFirstModelGenerationException( string.Format(Resources.ErrorGeneratingCodeFirstModel, entityTypeFileName), ex); } yield return new KeyValuePair<string, string>(entityTypeFileName, entityTypeFileContents); } } }
public IConfiguration Discover(EdmProperty property, DbModel model) { Debug.Assert(property != null, "property is null."); Debug.Assert(model != null, "model is null."); if (property.Nullable || property.PrimitiveType.ClrEquivalentType.IsValueType || property.IsKey() || model.GetColumn(property).IsTimestamp()) { // By convention return null; } return new RequiredConfiguration(); }
public IFluentConfiguration Discover(NavigationProperty navigationProperty, DbModel model) { Debug.Assert(navigationProperty != null, "navigationProperty is null."); Debug.Assert(model != null, "model is null."); var associationType = (AssociationType)navigationProperty.RelationshipType; if (!associationType.IsForeignKey || (navigationProperty.ToEndMember.RelationshipMultiplicity != RelationshipMultiplicity.Many && navigationProperty.FromEndMember.RelationshipMultiplicity != RelationshipMultiplicity.Many)) { // Doesn't apply return null; } var constraint = associationType.Constraint; var entityType = (EntityType)navigationProperty.DeclaringType; var fromProperty = constraint.FromProperties.First(); var fromPropertyName = fromProperty.Name; var toEntityType = navigationProperty.ToEndMember.GetEntityType(); // NOTE: OrderBy works around a bug in primary key column ordering (Work Item 868) var toProperties = constraint.ToProperties.OrderBy( p => entityType.KeyMembers.IndexOf(constraint.FromProperties[constraint.ToProperties.IndexOf(p)])); var toPropertyName = toProperties.First().Name; if (!toProperties.MoreThan(1) && (toPropertyName.EqualsIgnoreCase(navigationProperty.Name + fromPropertyName) || (!entityType.NavigationProperties.Where(p => p.ToEndMember.GetEntityType() == toEntityType) .MoreThan(1) && (toPropertyName.EqualsIgnoreCase(fromPropertyName) || toPropertyName.EqualsIgnoreCase(fromProperty.DeclaringType.Name + fromPropertyName))))) { // By convention return null; } var configuration = new ForeignKeyConfiguration(); foreach (var property in toProperties) { configuration.Properties.Add(property); } return configuration; }
public string Generate(DbModel model, string codeNamespace, string contextClassName, string connectionStringName) { Debug.Assert(model != null, "model is null."); Debug.Assert(!string.IsNullOrEmpty(codeNamespace), "codeNamespace is null or empty."); Debug.Assert(!string.IsNullOrEmpty(contextClassName), "contextClassName is null or empty."); Debug.Assert(!string.IsNullOrEmpty(connectionStringName), "connectionStringName is null or empty."); Session = new Dictionary<string, object> { { "Model", model }, { "Namespace", codeNamespace }, { "ContextClassName", contextClassName }, { "ConnectionStringName", connectionStringName } }; Initialize(); return TransformText(); }
public string Generate(DbModel model, string codeNamespace, string contextClassName, string connectionStringName) { var ctorComment = string.Format( CultureInfo.CurrentCulture, Resources.CodeFirstCodeFile_CtorComment_VB, contextClassName, codeNamespace); return string.Format( CultureInfo.CurrentCulture, VBCodeFileTemplate, contextClassName, ctorComment, connectionStringName, Resources.CodeFirstCodeFile_DbSetComment_VB); }
public IConfiguration Discover(EdmProperty property, DbModel model) { Debug.Assert(property != null, "property is null."); Debug.Assert(model != null, "model is null."); if (property.PrimitiveType.PrimitiveTypeKind != PrimitiveTypeKind.String) { // Doesn't apply return null; } if (property.IsUnicode == true) { // By convention return null; } return new NonUnicodeConfiguration(); }
public IConfiguration Discover(EdmProperty property, DbModel model) { Debug.Assert(property != null, "property is null."); Debug.Assert(model != null, "model is null."); var columnProperty = model.GetColumn(property); string name = null; if (_code.Property(property) != columnProperty.Name) { name = columnProperty.Name; } var providerManifest = model.GetProviderManifest(_dependencyResolver); var defaultTypeName = providerManifest.GetStoreType(property.TypeUsage) .EdmType.Name; string typeName = null; if (!columnProperty.TypeName.EqualsIgnoreCase(defaultTypeName)) { typeName = columnProperty.TypeName; } var entityType = (EntityType)property.DeclaringType; var keyIndex = entityType.KeyMembers.IndexOf(property); int? order = null; if (keyIndex != -1 && entityType.KeyMembers.Count > 1) { order = keyIndex; } if (name == null && typeName == null && order == null) { // By convention return null; } return new ColumnConfiguration { Name = name, TypeName = typeName, Order = order }; }
public IConfiguration Discover(EdmProperty property, DbModel model) { Debug.Assert(property != null, "property is null."); Debug.Assert(model != null, "model is null."); var keyProperties = ((EntityType)property.DeclaringType).KeyProperties; if (!keyProperties.Contains(property)) { // Doesn't apply return null; } if (keyProperties.Count == 1 && keyProperties.First().HasConventionalKeyName()) { // By convention return null; } return new KeyPropertyConfiguration(); }
public static DbModel CreateModel(DbProviderInfo provider) { if (_chinookModel == null) { var builder = new DbModelBuilder(); builder.Entity<Genre>(); builder.Entity<MediaType>(); builder.Entity<Artist>(); builder.Entity<Album>(); builder.Entity<Track>(); builder.Entity<Employee>(); builder.Entity<Customer>(); builder.Entity<Invoice>(); builder.Entity<InvoiceLine>(); builder.Entity<Playlist>(); builder.Entity<PlaylistTrack>(); _chinookModel = builder.Build(provider); } return _chinookModel; }
public override IConfiguration Discover(EdmProperty property, DbModel model) { Debug.Assert(property != null, "property is null."); Debug.Assert(model != null, "model is null."); if (!_lengthTypes.Contains(property.PrimitiveType.PrimitiveTypeKind)) { // Doesn't apply return null; } if (// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. property.IsFixedLength != true) { // By convention return null; } return new FixedLengthConfiguration(); }
public IConfiguration Discover(EdmProperty property, DbModel model) { Debug.Assert(property != null, "property is null."); Debug.Assert(model != null, "model is null."); if (property.PrimitiveType.PrimitiveTypeKind != PrimitiveTypeKind.Decimal) { // Doesn't apply return null; } var precision = property.Precision ?? 18; var scale = property.Scale ?? 2; if (precision == 18 && scale == 2) { // By convention return null; } return new PrecisionDecimalConfiguration { Precision = precision, Scale = scale }; }
public IFluentConfiguration Discover(NavigationProperty navigationProperty, DbModel model) { Debug.Assert(navigationProperty != null, "navigationProperty is null."); Debug.Assert(model != null, "model is null."); var fromEndMember = navigationProperty.FromEndMember; var toEndMember = navigationProperty.ToEndMember; if (fromEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many && toEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many) { // Doesn't apply return null; } var deleteBehavior = fromEndMember.RelationshipMultiplicity != RelationshipMultiplicity.Many && toEndMember.RelationshipMultiplicity != RelationshipMultiplicity.One ? fromEndMember.DeleteBehavior : toEndMember.DeleteBehavior; var defaultDeleteBehavior = (((fromEndMember.RelationshipMultiplicity == RelationshipMultiplicity.One && toEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many) || (fromEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many && toEndMember.RelationshipMultiplicity == RelationshipMultiplicity.One)) && fromEndMember.GetEntityType() != toEndMember.GetEntityType()) ? OperationAction.Cascade : OperationAction.None; if (deleteBehavior == defaultDeleteBehavior) { // By convention return null; } return new CascadeDeleteConfiguration { DeleteBehavior = deleteBehavior }; }
/// <summary> /// Saves a model to the store. /// </summary> /// <param name="contextType">The type of context representing the model.</param> /// <param name="model">The metadata model to save.</param> public abstract void Save(Type contextType, DbModel model);
/// <summary> /// Applies the convention to the given model. /// </summary> /// <param name="item"> The container to apply the convention to. </param> /// <param name="model"> The model. </param> public virtual void Apply(EntityContainer item, DbModel model) { Check.NotNull(model, "model"); item.Name = _containerName; }
/// <summary> /// Writes the Entity Data Model represented by the given <see cref="T:System.Data.Entity.Infrastructure.DbModel" /> to the /// given writer in EDMX form. /// </summary> /// <param name="model"> An object representing the EDM. </param> /// <param name="writer"> The writer. </param> public static void WriteEdmx(DbModel model, XmlWriter writer) { Check.NotNull <DbModel>(model, nameof(model)); Check.NotNull <XmlWriter>(writer, nameof(writer)); new EdmxSerializer().Serialize(model.DatabaseMapping, writer); }
/// <summary>Applies the convention to the given model.</summary> /// <param name="item"> The container to apply the convention to. </param> /// <param name="model"> The model. </param> public virtual void Apply(EntityContainer item, DbModel model) { Check.NotNull <DbModel>(model, nameof(model)); item.Name = this._containerName; }