public void ReverseEngineerCodeFirst() { try { // Find connection string and provider string connectionString = "data source=172.21.4.31,10086;initial catalog=Eme4;user id=eme;password=io77@68;MultipleActiveResultSets=True;App=EntityFramework""; var providerInvariant = "System.Data.SqlClient"; string projectNamespace = "TEST"; string currentDirectory = System.IO.Directory.GetCurrentDirectory(); DbConnection connection = new SqlConnection(connectionString); // Load store schema var storeGenerator = new EntityStoreSchemaGenerator(providerInvariant, connectionString, "dbo"); storeGenerator.GenerateForeignKeyProperties = true; var errors = storeGenerator.GenerateStoreMetadata(_storeMetadataFilters).Where(e => e.Severity == EdmSchemaErrorSeverity.Error); // Generate default mapping var contextName = connection.Database.Replace(" ", string.Empty).Replace(".", string.Empty) + "Context"; var modelGenerator = new EntityModelSchemaGenerator(storeGenerator.EntityContainer, "DefaultNamespace", contextName); modelGenerator.PluralizationService = PluralizationService.CreateService(new CultureInfo("en")); modelGenerator.GenerateForeignKeyProperties = true; modelGenerator.GenerateMetadata(); // Pull out info about types to be generated var entityTypes = modelGenerator.EdmItemCollection.OfType <EntityType>().ToArray(); var mappings = new EdmMapping(modelGenerator, storeGenerator.StoreItemCollection); // Generate Entity Classes and Mappings var templateProcessor = new TemplateProcessor(); var modelsNamespace = projectNamespace + ".Models"; var modelsDirectory = Path.Combine(currentDirectory, "Models"); var mappingNamespace = modelsNamespace + ".Mapping"; var mappingDirectory = Path.Combine(modelsDirectory, "Mapping"); var entityFrameworkVersion = GetEntityFrameworkVersion(); foreach (var entityType in entityTypes) { // Generate the code file var entityHost = new EfTextTemplateHost { EntityType = entityType, EntityContainer = modelGenerator.EntityContainer, Namespace = modelsNamespace, ModelsNamespace = modelsNamespace, MappingNamespace = mappingNamespace, EntityFrameworkVersion = entityFrameworkVersion, TableSet = mappings.EntityMappings[entityType].Item1, PropertyToColumnMappings = mappings.EntityMappings[entityType].Item2, ManyToManyMappings = mappings.ManyToManyMappings }; var entityContents = templateProcessor.Process(Templates.EntityTemplate, entityHost); var filePath = Path.Combine(modelsDirectory, entityType.Name + entityHost.FileExtension); FileGenerator.AddNewFile(filePath, entityContents); var mappingHost = new EfTextTemplateHost { EntityType = entityType, EntityContainer = modelGenerator.EntityContainer, Namespace = mappingNamespace, ModelsNamespace = modelsNamespace, MappingNamespace = mappingNamespace, EntityFrameworkVersion = entityFrameworkVersion, TableSet = mappings.EntityMappings[entityType].Item1, PropertyToColumnMappings = mappings.EntityMappings[entityType].Item2, ManyToManyMappings = mappings.ManyToManyMappings }; var mappingContents = templateProcessor.Process(Templates.MappingTemplate, mappingHost); var mappingFilePath = Path.Combine(mappingDirectory, entityType.Name + "Map" + mappingHost.FileExtension); FileGenerator.AddNewFile(filePath, entityContents); } // Generate Context var contextHost = new EfTextTemplateHost { EntityContainer = modelGenerator.EntityContainer, Namespace = modelsNamespace, ModelsNamespace = modelsNamespace, MappingNamespace = mappingNamespace, EntityFrameworkVersion = entityFrameworkVersion }; var contextContents = templateProcessor.Process(Templates.ContextTemplate, contextHost); var contextFilePath = Path.Combine(modelsDirectory, modelGenerator.EntityContainer.Name + contextHost.FileExtension); FileGenerator.AddNewFile(contextFilePath, contextContents); } catch (Exception exception) { } }
// End Added ErikEJ #region the functions that actually do the interesting things private static void ModelGen( string connectionString, string provider, string modelName, Version version, bool includeForeignKeys, bool pluralize, List <string> tables) { IList <EdmSchemaError> ssdlErrors = null; IList <EdmSchemaError> csdlAndMslErrors = null; // generate the SSDL string ssdlNamespace = modelName + "Model.Store"; EntityStoreSchemaGenerator essg = new EntityStoreSchemaGenerator( provider, connectionString, ssdlNamespace); essg.GenerateForeignKeyProperties = includeForeignKeys; //ErikEJ Filter selected tables var filters = new List <EntityStoreSchemaFilterEntry>(); foreach (var table in tables) { var entry = new EntityStoreSchemaFilterEntry(null, null, table); filters.Add(entry); } ssdlErrors = essg.GenerateStoreMetadata(filters, version); // detect if there are errors or only warnings from ssdl generation bool hasSsdlErrors = false; bool hasSsdlWarnings = false; if (ssdlErrors != null) { foreach (EdmSchemaError e in ssdlErrors) { if (e.Severity == EdmSchemaErrorSeverity.Error) { hasSsdlErrors = true; } else if (e.Severity == EdmSchemaErrorSeverity.Warning) { hasSsdlWarnings = true; } } } // write out errors & warnings if (hasSsdlErrors && hasSsdlWarnings) { //System.Console.WriteLine("Errors occurred during generation:"); WriteErrors(ssdlErrors); } // if there were errors abort. Continue if there were only warnings if (hasSsdlErrors) { return; } // write the SSDL to a string using (StringWriter ssdl = new StringWriter()) { XmlWriter ssdlxw = XmlWriter.Create(ssdl); essg.WriteStoreSchema(ssdlxw); ssdlxw.Flush(); // generate the CSDL string csdlNamespace = modelName + "Model"; string csdlEntityContainerName = modelName + "Entities"; EntityModelSchemaGenerator emsg = new EntityModelSchemaGenerator( essg.EntityContainer, csdlNamespace, csdlEntityContainerName); emsg.GenerateForeignKeyProperties = includeForeignKeys; // Begin Added ErikEJ if (pluralize) { emsg.PluralizationService = System.Data.Entity.Design.PluralizationServices.PluralizationService.CreateService(new System.Globalization.CultureInfo("en-US")); } // End Added ErikEJ csdlAndMslErrors = emsg.GenerateMetadata(version); // detect if there are errors or only warnings from csdl/msl generation bool hasCsdlErrors = false; bool hasCsdlWarnings = false; if (csdlAndMslErrors != null) { foreach (EdmSchemaError e in csdlAndMslErrors) { if (e.Severity == EdmSchemaErrorSeverity.Error) { hasCsdlErrors = true; } else if (e.Severity == EdmSchemaErrorSeverity.Warning) { hasCsdlWarnings = true; } } } // write out errors & warnings if (hasCsdlErrors || hasCsdlWarnings) { //System.Console.WriteLine("Errors occurred during generation:"); WriteErrors(csdlAndMslErrors); } // if there were errors, abort. Don't abort if there were only warnigns. if (hasCsdlErrors) { return; } // write CSDL to a string using (StringWriter csdl = new StringWriter()) { XmlWriter csdlxw = XmlWriter.Create(csdl); emsg.WriteModelSchema(csdlxw); csdlxw.Flush(); // write MSL to a string using (StringWriter msl = new StringWriter()) { XmlWriter mslxw = XmlWriter.Create(msl); emsg.WriteStorageMapping(mslxw); mslxw.Flush(); // write csdl, ssdl & msl to the EDMX file ToEdmx( csdl.ToString(), ssdl.ToString(), msl.ToString(), new FileInfo( modelName + ".edmx"), includeForeignKeys, pluralize); } } } }
public void ReverseEngineerCodeFirst(Project project, EntityModelSchemaGenerator modelGenerator, EntityType[] entityTypes, StoreItemCollection StoreItemCollection, Version entityFrameworkVersion) { DebugCheck.NotNull(project); try { var mappings = new EdmMapping(modelGenerator, StoreItemCollection); var projectNamespace = (string)project.Properties.Item("RootNamespace").Value; var reverseEngineerCodeFirstFolder = new DirectoryInfo(Path.Combine(project.GetProjectDir(), "CodeTemplates", "ReverseEngineerCodeFirst")); if (!reverseEngineerCodeFirstFolder.Exists) { return; } var t4Files = reverseEngineerCodeFirstFolder.GetFiles().Where(p => p.Extension == ".tt"); if (!t4Files.Any()) { return; } // Generate Entity Classes and Mappings var templateProcessor = new TemplateProcessor(project); foreach (var file in t4Files) { if (file.Length == 0) { continue; } #region 特殊处理Context if (file.Name.ToLower().EndsWith("context.tt")) { package.LogInfo("Context"); var contextHost = new EfTextTemplateHost { EntityContainer = modelGenerator.EntityContainer, Namespace = projectNamespace, EntityFrameworkVersion = entityFrameworkVersion }; SaveProjectFile(project, contextHost, templateProcessor, modelGenerator.EntityContainer.Name.Replace("Context", ""), "Models", "Context.tt"); continue; } #endregion #region 实体处理 var fileName = file.Name.Replace(".tt", ""); fileName = fileName.EndsWith("s") ? fileName : fileName + "s"; foreach (var entityType in entityTypes) { package.LogInfo(file.FullName + "|" + entityType.Name); var efHost = new EfTextTemplateHost { EntityType = entityType, EntityContainer = modelGenerator.EntityContainer, Namespace = projectNamespace, EntityFrameworkVersion = entityFrameworkVersion, TableSet = mappings.EntityMappings[entityType].Item1, PropertyToColumnMappings = mappings.EntityMappings[entityType].Item2, ManyToManyMappings = mappings.ManyToManyMappings }; SaveProjectFile(project, efHost, templateProcessor, entityType.Name, fileName, file.Name); } #endregion } } catch (Exception exception) { package.LogError(project.Name + "生成出错", exception); } }
public void ReverseEngineerCodeFirstMain(Project project) { DebugCheck.NotNull(project); targetProject = project; try { var startTime = DateTime.Now; var _storeMetadataFilters = new List <EntityStoreSchemaFilterEntry> { new EntityStoreSchemaFilterEntry(null, null, "EdmMetadata", EntityStoreSchemaFilterObjectTypes.Table, EntityStoreSchemaFilterEffect.Exclude), new EntityStoreSchemaFilterEntry(null, null, "__MigrationHistory", EntityStoreSchemaFilterObjectTypes.Table, EntityStoreSchemaFilterEffect.Exclude), new EntityStoreSchemaFilterEntry(null, null, "sysdiagrams", EntityStoreSchemaFilterObjectTypes.Table, EntityStoreSchemaFilterEffect.Exclude), //new EntityStoreSchemaFilterEntry(null, null, null, EntityStoreSchemaFilterObjectTypes.View, EntityStoreSchemaFilterEffect.Exclude), new EntityStoreSchemaFilterEntry(null, null, null, EntityStoreSchemaFilterObjectTypes.Function, EntityStoreSchemaFilterEffect.Exclude) }; //build.txt不存在或者空文本生成所有实体,有文本按设置生成 var buildFilename = Path.Combine(targetProject.GetProjectDir(), "build.txt"); if (File.Exists(buildFilename)) { var content = File.ReadAllText(buildFilename); if (!string.IsNullOrWhiteSpace(content)) { var allowFilterEntrys = content.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries) .Select(p => new EntityStoreSchemaFilterEntry(null, null, p, EntityStoreSchemaFilterObjectTypes.Table, EntityStoreSchemaFilterEffect.Allow)); _storeMetadataFilters.AddRange(allowFilterEntrys); } } var connectionStringSettings = DoConnectionStringSettings(targetProject); var entityFrameworkVersion = GetEntityFrameworkVersion(package, targetProject); // Load store schema var storeGenerator = new EntityStoreSchemaGenerator(connectionStringSettings.ProviderName, connectionStringSettings.ConnectionString, "dbo"); storeGenerator.GenerateForeignKeyProperties = true; var errors = storeGenerator.GenerateStoreMetadata(_storeMetadataFilters).Where(e => e.Severity == EdmSchemaErrorSeverity.Error); errors.HandleErrors(Strings.ReverseEngineer_SchemaError); if (storeGenerator.EntityContainer.BaseEntitySets == null || storeGenerator.EntityContainer.BaseEntitySets.Count() == 0) { package.LogError("生成中断,没有找到对应的表", new Exception("生成中断,没有找到对应的表")); return; } // Generate default mapping package.LogInfo(Strings.ReverseEngineer_GenerateMapping); var modelGenerator = new EntityModelSchemaGenerator(storeGenerator.EntityContainer, "DefaultNamespace", connectionStringSettings.Name); modelGenerator.PluralizationService = PluralizationService.CreateService(new CultureInfo("en")); modelGenerator.GenerateForeignKeyProperties = true; modelGenerator.GenerateMetadata(); var entityTypes = modelGenerator.EdmItemCollection.OfType <EntityType>().ToArray(); EdmPropertyExtension.ColumnModels = new DocumentionExtension().GenerateDocumentation(entityTypes, connectionStringSettings); EntityTypeExtension.GetTableDescriptions(connectionStringSettings); var solutionProjects = targetProject.DTE.Solution.Projects.OfType <Project>(); Action <IEnumerable <Project> > loopProjectsAction = null; loopProjectsAction = projects => { foreach (var item in projects) { if (item.FullName.EndsWith(".csproj")) { ReverseEngineerCodeFirst(item, modelGenerator, entityTypes, storeGenerator.StoreItemCollection, entityFrameworkVersion); continue; } if (item.ProjectItems.Count > 0) { var subProjects = new List <Project>(); foreach (EnvDTE.ProjectItem subProject in item.ProjectItems) { subProjects.Add(subProject.SubProject); } loopProjectsAction(subProjects); } } }; loopProjectsAction(solutionProjects); var duration = DateTime.Now - startTime; package.LogInfo(Strings.ReverseEngineer_Complete(duration.ToString(@"h\:mm\:ss"))); } catch (Exception exception) { package.LogError(exception.Message, exception); } }
public void ReverseEngineerCodeFirst(Project project) { DebugCheck.NotNull(project); try { Stopwatch watcher = new Stopwatch(); watcher.Start(); string connectionString = string.Empty; string providerInvariant = string.Empty; string databaseName = string.Empty; bool isNewConnectionString = false; // Show available connection string var existingConnections = GetConnectionstrings(project); Connections connectionDialog = new Connections(existingConnections.Select(x => x.Name)); connectionDialog.ShowModal(); if (connectionDialog.IsConnectionStringSelected) { var selected = connectionDialog.SelectedConnectionString; var selectedConnectionSetting = existingConnections.First(x => x.Name.Equals(selected)); providerInvariant = selectedConnectionSetting.ProviderName; connectionString = selectedConnectionSetting.ConnectionString; var dbConnection = DbProviderFactories.GetFactory(providerInvariant).CreateConnection(); dbConnection.ConnectionString = connectionString; databaseName = dbConnection.Database; } else { // Show dialog with SqlClient selected by default var dialogFactory = _package.GetService <IVsDataConnectionDialogFactory>(); var dialog = dialogFactory.CreateConnectionDialog(); dialog.AddAllSources(); dialog.SelectedSource = new Guid("067ea0d9-ba62-43f7-9106-34930c60c528"); var dialogResult = dialog.ShowDialog(connect: true); if (dialogResult != null) { // Find connection string and provider var connection = (DbConnection)dialogResult.GetLockedProviderObject(); connectionString = connection.ConnectionString; var providerManager = (IVsDataProviderManager)Package.GetGlobalService(typeof(IVsDataProviderManager)); IVsDataProvider dp; providerManager.Providers.TryGetValue(dialogResult.Provider, out dp); providerInvariant = (string)dp.GetProperty("InvariantName"); databaseName = connection.Database; isNewConnectionString = true; } else { // User selected not to proceed by clicking cancel or closes window. return; } } // Load store schema _package.DTE2.StatusBar.Text = Strings.ReverseEngineer_LoadingSchema; var storeGenerator = new EntityStoreSchemaGenerator(providerInvariant, connectionString, "dbo"); storeGenerator.GenerateForeignKeyProperties = true; var errors = storeGenerator.GenerateStoreMetadata(_storeMetadataFilters).Where(e => e.Severity == EdmSchemaErrorSeverity.Error); errors.HandleErrors(Strings.ReverseEngineer_SchemaError); // Generate default mapping _package.DTE2.StatusBar.Text = Strings.ReverseEngineer_GenerateMapping; var contextName = databaseName.Replace(" ", string.Empty).Replace(".", string.Empty) + "Context"; var modelGenerator = new EntityModelSchemaGenerator(storeGenerator.EntityContainer, "DefaultNamespace", contextName); modelGenerator.PluralizationService = PluralizationService.CreateService(new CultureInfo("en")); modelGenerator.GenerateForeignKeyProperties = true; modelGenerator.GenerateMetadata(); // Pull out info about types to be generated var entityTypes = modelGenerator.EdmItemCollection.OfType <EntityType>().ToArray(); var mappings = new EdmMapping(modelGenerator, storeGenerator.StoreItemCollection); // Find the project to add the code to var vsProject = (VSLangProj.VSProject)project.Object; var projectDirectory = new FileInfo(project.FileName).Directory; var defaultProjectNameSpace = (string)project.Properties.Item("RootNamespace").Value; var references = vsProject.References.Cast <VSLangProj.Reference>(); if (!references.Any(r => r.Name == "EntityFramework")) { // Add EF References _package.DTE2.StatusBar.Text = Strings.ReverseEngineer_InstallEntityFramework; try { project.InstallPackage("EntityFramework"); } catch (Exception ex) { _package.LogError(Strings.ReverseEngineer_InstallEntityFrameworkError, ex); } } // Generate Entity Classes and Mappings var templateProcessor = new TemplateProcessor(project); var modelsNamespaceSuffixDefault = "Models"; var mappingNamespaceSuffixDefault = "Mappings"; var projectNamespace = defaultProjectNameSpace; var modelsNamespace = string.Concat(projectNamespace, ".", modelsNamespaceSuffixDefault); var mappingNamespace = string.Concat(modelsNamespace, ".", mappingNamespaceSuffixDefault); var modelsDirectory = projectDirectory.FullName; var mappingDirectory = projectDirectory.FullName; var contextDirectory = projectDirectory.FullName; var entityFrameworkVersion = GetEntityFrameworkVersion(references); ConcurrentDictionary <string, string> models = new ConcurrentDictionary <string, string>(); ConcurrentDictionary <string, string> maps = new ConcurrentDictionary <string, string>(); // Process the templates and generate content Parallel.ForEach(entityTypes, (entityType) => { _package.DTE2.StatusBar.Text = Strings.ReverseEngineer_GenerateClasses(entityType.Name); var entityHost = new EfTextTemplateHost { EntityType = entityType, EntityContainer = modelGenerator.EntityContainer, Namespace = projectNamespace, ModelsNamespace = modelsNamespace, MappingNamespace = mappingNamespace, EntityFrameworkVersion = entityFrameworkVersion, TableSet = mappings.EntityMappings[entityType].Item1, PropertyToColumnMappings = mappings.EntityMappings[entityType].Item2, ManyToManyMappings = mappings.ManyToManyMappings }; var entityContents = templateProcessor.Process(Templates.EntityTemplate, entityHost); models.TryAdd(entityType.Name + entityHost.FileExtension, entityContents); var mappingHost = new EfTextTemplateHost { EntityType = entityType, EntityContainer = modelGenerator.EntityContainer, Namespace = projectNamespace, ModelsNamespace = modelsNamespace, MappingNamespace = mappingNamespace, EntityFrameworkVersion = entityFrameworkVersion, TableSet = mappings.EntityMappings[entityType].Item1, PropertyToColumnMappings = mappings.EntityMappings[entityType].Item2, ManyToManyMappings = mappings.ManyToManyMappings }; var mappingContents = templateProcessor.Process(Templates.MappingTemplate, mappingHost); maps.TryAdd(entityType.Name + "Map" + mappingHost.FileExtension, mappingContents); }); // Generate Context _package.DTE2.StatusBar.Text = Strings.ReverseEngineer_GenerateContext; var contextHost = new EfTextTemplateHost { EntityContainer = modelGenerator.EntityContainer, Namespace = projectNamespace, ModelsNamespace = modelsNamespace, MappingNamespace = mappingNamespace, EntityFrameworkVersion = entityFrameworkVersion }; var contextContents = templateProcessor.Process(Templates.ContextTemplate, contextHost); ProjectFilesPathGenUtility.SyncDirectoryWithNamespace( defaultProjectNameSpace, contextHost.Namespace, modelsNamespaceSuffixDefault, projectDirectory.FullName, ref contextDirectory); var contextFilePath = Path.Combine(contextDirectory, modelGenerator.EntityContainer.Name + contextHost.FileExtension); _package.DTE2.StatusBar.Text = Strings.ReverseEngineer_AddingFiles; var contextItem = project.AddNewFile(contextFilePath, contextContents); // sync model directory ProjectFilesPathGenUtility.SyncDirectoryWithNamespace( defaultProjectNameSpace, contextHost.ModelsNamespace, modelsNamespaceSuffixDefault, projectDirectory.FullName, ref modelsDirectory); // Add models Parallel.ForEach(models, (file) => { project.AddNewFile(Path.Combine(modelsDirectory, file.Key), file.Value); }); // sync project mapping directory ProjectFilesPathGenUtility.SyncDirectoryWithNamespace( defaultProjectNameSpace, contextHost.MappingNamespace, mappingNamespaceSuffixDefault, projectDirectory.FullName, ref mappingDirectory); // Add mappings Parallel.ForEach(maps, (file) => { project.AddNewFile(Path.Combine(mappingDirectory, file.Key), file.Value); }); if (isNewConnectionString) { AddConnectionStringToConfigFile(project, connectionString, providerInvariant, modelGenerator.EntityContainer.Name); } if (contextItem != null) { // Open context class when done _package.DTE2.ItemOperations.OpenFile(contextFilePath); } watcher.Stop(); _package.DTE2.StatusBar.Text = Strings.ReverseEngineer_Complete((int)watcher.Elapsed.TotalSeconds); } catch (Exception exception) { _package.LogError(Strings.ReverseEngineer_Error, exception); } }
public void CodeGenerator(string connectionString, string projectNamespace, Action <string> action, List <string> selectedTables) { try { // Find connection string and provider var providerInvariant = "System.Data.SqlClient"; string currentDirectory = System.IO.Directory.GetCurrentDirectory(); using (DbConnection connection = new SqlConnection(connectionString)) { // Load store schema var storeGenerator = new EntityStoreSchemaGenerator(providerInvariant, connectionString, "dbo"); storeGenerator.GenerateForeignKeyProperties = true; var errors = storeGenerator.GenerateStoreMetadata(_storeMetadataFilters).Where(e => e.Severity == EdmSchemaErrorSeverity.Error); // Generate default mapping var contextName = connection.Database.Replace(" ", string.Empty).Replace(".", string.Empty) + "Context"; var modelGenerator = new EntityModelSchemaGenerator(storeGenerator.EntityContainer, "DefaultNamespace", contextName); modelGenerator.PluralizationService = PluralizationService.CreateService(new CultureInfo("en")); modelGenerator.GenerateForeignKeyProperties = true; modelGenerator.GenerateMetadata(); // Pull out info about types to be generated var entityTypes = modelGenerator.EdmItemCollection.OfType <EntityType>().ToArray().ToList(); var mappings = new EdmMapping(modelGenerator, storeGenerator.StoreItemCollection); var templateProcessor = new TemplateProcessor(); entityTypes = HandleCompletedRun(entityTypes, selectedTables); TemplateCommon.projectNamespace = projectNamespace; TemplateCommon.entityFrameworkVersion = GetEntityFrameworkVersion(); TemplateCommon.Init(); foreach (var entityType in entityTypes) { var entityName = entityType.Name.RemoveSpecialChar(); EntityTemplate entityTemplate = new EntityTemplate(entityType); entityTemplate.Generator(modelGenerator, templateProcessor, mappings); // Generate the map file new MappingTemplate(entityType).Generator(modelGenerator, templateProcessor, mappings); //Generate the repository file new RepositoryTemplate(entityType).Generator(modelGenerator, templateProcessor, mappings); //Generate the service file new ServiceTemplate(entityType).Generator(modelGenerator, templateProcessor, mappings); //Generate the svc file new SvcTemplate(entityType).Generator(modelGenerator, templateProcessor, mappings); //Generate the svc test file new SvcTestTemplate(entityType).Generator(modelGenerator, templateProcessor, mappings); } // Generate Context new ContextTemplate().Generator(modelGenerator, templateProcessor, mappings); if (action != null) { action("代码生成成功"); } } } catch (Exception exception) { if (action != null) { action(exception.Message); } } }
public void ReverseEngineerCodeFirst(Project project) { DebugCheck.NotNull(project); try { var startTime = DateTime.Now; // Show dialog with SqlClient selected by default var dialogFactory = _package.GetService <IVsDataConnectionDialogFactory>(); var dialog = dialogFactory.CreateConnectionDialog(); dialog.AddAllSources(); dialog.SelectedSource = new Guid("067ea0d9-ba62-43f7-9106-34930c60c528"); var dialogResult = dialog.ShowDialog(connect: true); if (dialogResult != null) { // Find connection string and provider _package.DTE2.StatusBar.Text = Strings.ReverseEngineer_LoadSchema; var connection = (DbConnection)dialogResult.GetLockedProviderObject(); var connectionString = connection.ConnectionString; var providerManager = (IVsDataProviderManager)Package.GetGlobalService(typeof(IVsDataProviderManager)); IVsDataProvider dp; providerManager.Providers.TryGetValue(dialogResult.Provider, out dp); var providerInvariant = (string)dp.GetProperty("InvariantName"); // Load store schema var storeGenerator = new EntityStoreSchemaGenerator(providerInvariant, connectionString, "dbo"); storeGenerator.GenerateForeignKeyProperties = true; var errors = storeGenerator.GenerateStoreMetadata(_storeMetadataFilters).Where(e => e.Severity == EdmSchemaErrorSeverity.Error); errors.HandleErrors(Strings.ReverseEngineer_SchemaError); // Generate default mapping _package.DTE2.StatusBar.Text = Strings.ReverseEngineer_GenerateMapping; var contextName = connection.Database.Replace(" ", string.Empty).Replace(".", string.Empty) + "Context"; var modelGenerator = new EntityModelSchemaGenerator(storeGenerator.EntityContainer, "DefaultNamespace", contextName); modelGenerator.PluralizationService = PluralizationService.CreateService(new CultureInfo("en")); modelGenerator.GenerateForeignKeyProperties = true; modelGenerator.GenerateMetadata(); // Pull out info about types to be generated var entityTypes = modelGenerator.EdmItemCollection.OfType <EntityType>().ToArray(); var mappings = new EdmMapping(modelGenerator, storeGenerator.StoreItemCollection); // Find the project to add the code to var vsProject = (VSLangProj.VSProject)project.Object; var projectDirectory = new FileInfo(project.FileName).Directory; var projectNamespace = (string)project.Properties.Item("RootNamespace").Value; var references = vsProject.References.Cast <VSLangProj.Reference>(); if (!references.Any(r => r.Name == "EntityFramework")) { // Add EF References _package.DTE2.StatusBar.Text = Strings.ReverseEngineer_InstallEntityFramework; try { project.InstallPackage("EntityFramework"); } catch (Exception ex) { _package.LogError(Strings.ReverseEngineer_InstallEntityFrameworkError, ex); } } // Generate Entity Classes and Mappings var templateProcessor = new TemplateProcessor(project); var modelsNamespace = projectNamespace + ".Models"; var modelsDirectory = Path.Combine(projectDirectory.FullName, "Models"); var mappingNamespace = modelsNamespace + ".Mapping"; var mappingDirectory = Path.Combine(modelsDirectory, "Mapping"); var entityFrameworkVersion = GetEntityFrameworkVersion(references); foreach (var entityType in entityTypes) { _package.DTE2.StatusBar.Text = Strings.ReverseEngineer_GenerateClasses(entityType.Name); // Generate the code file var entityHost = new EfTextTemplateHost { EntityType = entityType, EntityContainer = modelGenerator.EntityContainer, Namespace = modelsNamespace, ModelsNamespace = modelsNamespace, MappingNamespace = mappingNamespace, EntityFrameworkVersion = entityFrameworkVersion, TableSet = mappings.EntityMappings[entityType].Item1, PropertyToColumnMappings = mappings.EntityMappings[entityType].Item2, ManyToManyMappings = mappings.ManyToManyMappings }; var entityContents = templateProcessor.Process(Templates.EntityTemplate, entityHost); var filePath = Path.Combine(modelsDirectory, entityType.Name + entityHost.FileExtension); project.AddNewFile(filePath, entityContents); var mappingHost = new EfTextTemplateHost { EntityType = entityType, EntityContainer = modelGenerator.EntityContainer, Namespace = mappingNamespace, ModelsNamespace = modelsNamespace, MappingNamespace = mappingNamespace, EntityFrameworkVersion = entityFrameworkVersion, TableSet = mappings.EntityMappings[entityType].Item1, PropertyToColumnMappings = mappings.EntityMappings[entityType].Item2, ManyToManyMappings = mappings.ManyToManyMappings }; var mappingContents = templateProcessor.Process(Templates.MappingTemplate, mappingHost); var mappingFilePath = Path.Combine(mappingDirectory, entityType.Name + "Map" + mappingHost.FileExtension); project.AddNewFile(mappingFilePath, mappingContents); } // Generate Context _package.DTE2.StatusBar.Text = Strings.ReverseEngineer_GenerateContext; var contextHost = new EfTextTemplateHost { EntityContainer = modelGenerator.EntityContainer, Namespace = modelsNamespace, ModelsNamespace = modelsNamespace, MappingNamespace = mappingNamespace, EntityFrameworkVersion = entityFrameworkVersion }; var contextContents = templateProcessor.Process(Templates.ContextTemplate, contextHost); var contextFilePath = Path.Combine(modelsDirectory, modelGenerator.EntityContainer.Name + contextHost.FileExtension); var contextItem = project.AddNewFile(contextFilePath, contextContents); AddConnectionStringToConfigFile(project, connectionString, providerInvariant, modelGenerator.EntityContainer.Name); if (contextItem != null) { // Open context class when done _package.DTE2.ItemOperations.OpenFile(contextFilePath); } var duration = DateTime.Now - startTime; _package.DTE2.StatusBar.Text = Strings.ReverseEngineer_Complete(duration.ToString(@"h\:mm\:ss")); } } catch (Exception exception) { _package.LogError(Strings.ReverseEngineer_Error, exception); } }
internal override bool Generate() { IList <EdmSchemaError> errors = null; // generate the SSDL string ssdlNamespace = _modelName + "Model.Store"; EntityStoreSchemaGenerator essg = new EntityStoreSchemaGenerator(ProviderName, _con.ConnectionString, ssdlNamespace); List <EntityStoreSchemaFilterEntry> filters = new List <EntityStoreSchemaFilterEntry>(); if (_tables != null && _tables.Count > 0) { foreach (var tablename in _tables) { filters.Add(new EntityStoreSchemaFilterEntry(null, null, tablename, EntityStoreSchemaFilterObjectTypes.Table, EntityStoreSchemaFilterEffect.Allow)); } } else { filters.Add(new EntityStoreSchemaFilterEntry(null, null, _table, EntityStoreSchemaFilterObjectTypes.Table, EntityStoreSchemaFilterEffect.Allow)); } filters.Add(new EntityStoreSchemaFilterEntry(null, null, "%", EntityStoreSchemaFilterObjectTypes.View, EntityStoreSchemaFilterEffect.Exclude)); Version entityVersion = new Version(2, 0, 0, 0); #if NET_40_OR_GREATER errors = essg.GenerateStoreMetadata(filters, entityVersion); #else errors = essg.GenerateStoreMetadata(filters); #endif // write out errors if ((errors != null && errors.Count > 0)) { WriteErrors(errors); SendErrorsToGeneralOuput(); } // write the SSDL to a string StringWriter ssdl = new StringWriter(); XmlWriter ssdlxw = XmlWriter.Create(ssdl); essg.WriteStoreSchema(ssdlxw); ssdlxw.Flush(); // generate the CSDL string csdlNamespace = _artifactNamespace; string csdlEntityContainerName = _modelName + "Entities"; EntityModelSchemaGenerator emsg = new EntityModelSchemaGenerator(essg.EntityContainer, csdlNamespace, csdlEntityContainerName); #if NET_40_OR_GREATER emsg.GenerateForeignKeyProperties = true; errors = emsg.GenerateMetadata(entityVersion); #else errors = emsg.GenerateMetadata(); #endif // write out errors if ((errors != null && errors.Count > 0)) { WriteErrors(errors); SendErrorsToGeneralOuput(); } // write CSDL to a string StringWriter csdl = new StringWriter(); XmlWriter csdlxw = XmlWriter.Create(csdl); emsg.WriteModelSchema(csdlxw); csdlxw.Flush(); // write MSL to a string StringWriter msl = new StringWriter(); XmlWriter mslxw = XmlWriter.Create(msl, new XmlWriterSettings() { }); emsg.WriteStorageMapping(mslxw); mslxw.Flush(); // Write everything + glue xml to file string file = Path.Combine(_path, _modelName + ".edmx"); string sCsdl = csdl.ToString(); string sSsdl = ssdl.ToString(); string sMsl = msl.ToString(); sCsdl = sCsdl.Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", ""); sSsdl = sSsdl.Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", ""); sMsl = sMsl.Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", ""); FileInfo fi = new FileInfo(file); WriteEdmx(sCsdl, sSsdl, sMsl, fi); if (_mappings != null && _mappings.Count != 0) { GetColumnMappings(fi); } AddToProject(fi.FullName); if (_warnings.Count > 0) { SendErrorsToGeneralOuput(); _tablesIncluded = GetTablesInModel(fi.FullName); } else { _tablesIncluded = _tables; } return(true); }
private void HydrateTypeInfo(EntityStoreSchemaGenerator schema, EntityModelSchemaGenerator mappings) { EntityTypes = mappings.EdmItemCollection.OfType <EntityType>().ToArray(); Mappings = new EdmMapping(mappings, schema.StoreItemCollection); }