示例#1
0
        internal static string ReverseEngineerCodeFirst(
            string modelsNamespace,
            string schema,
            string connectionString,
            string providerInvariant = "System.Data.SqlClient")
        {
            SqlConnection connection = new SqlConnection(connectionString);

            // Load store schema
            EntityStoreSchemaGenerator _EntityStoreSchemaGenerator = new EntityStoreSchemaGenerator(providerInvariant, connectionString, "dbo")
            {
                GenerateForeignKeyProperties = true
            };

            _EntityStoreSchemaGenerator.GenerateStoreMetadata(new[] { new EntityStoreSchemaFilterEntry(null, schema, null, EntityStoreSchemaFilterObjectTypes.Table, EntityStoreSchemaFilterEffect.Allow) });


            // Generate default mapping
            string contextName = connection
                                 .Database
                                 .Replace(" ", string.Empty)
                                 .Replace(".", string.Empty) + "Context";

            EntityModelSchemaGenerator _EntityModelSchemaGenerator =
                new EntityModelSchemaGenerator(
                    _EntityStoreSchemaGenerator.EntityContainer,
                    modelsNamespace,
                    contextName)
            {
                GenerateForeignKeyProperties = false
            };

            _EntityModelSchemaGenerator.GenerateMetadata();

            // Pull out info about types to be generated
            EntityType[] _EntityTypes = _EntityModelSchemaGenerator.EdmItemCollection.OfType <EntityType>().ToArray();
            EdmMapping   _EdmMapping  = new EdmMapping(_EntityModelSchemaGenerator, _EntityStoreSchemaGenerator.StoreItemCollection);

            string result = string.Empty;

            foreach (EntityType type in _EntityTypes)
            {
                result = result + new Entity
                {
                    Host = new TextTemplatingEngineHost
                    {
                        EntityType               = type,
                        EntityContainer          = _EntityModelSchemaGenerator.EntityContainer,
                        Namespace                = modelsNamespace,
                        TableSet                 = _EdmMapping.EntityMappings[type].Item1,
                        PropertyToColumnMappings = _EdmMapping.EntityMappings[type].Item2,
                        ManyToManyMappings       = _EdmMapping.ManyToManyMappings
                    }
                }
            }
示例#2
0
        public void BlahBlah()
        {
            var sampleGeneratorFactory = new SampleGeneratorFactory(
                CodeFirstGen.OneToMany.Csdl(),
                CodeFirstGen.OneToMany.Ssdl(),
                CodeFirstGen.OneToMany.Msdl());

            var aa = sampleGeneratorFactory.StoreItemCollection.Last();
            var ab = sampleGeneratorFactory.ConceptualItemCollection.Last();

            var edmMapping = new EdmMapping(
                sampleGeneratorFactory.ConceptualItemCollection,
                sampleGeneratorFactory.StoreItemCollection,
                CodeFirstGen.OneToMany.Msdl());
        }
        public void Generator(EntityModelSchemaGenerator modelGenerator, TemplateProcessor templateProcessor, EdmMapping mappings)
        {
            var entityName = EntityType.Name.RemoveSpecialChar();
            // Generate the entity file
            var entityHost = new EfTextTemplateHost
            {
                EntityType             = EntityType,
                EntityContainer        = modelGenerator.EntityContainer,
                Namespace              = Namespace,
                ModelsNamespace        = Namespace,
                MappingNamespace       = TemplateCommon.mappingNamespace,
                EntityFrameworkVersion = TemplateCommon.entityFrameworkVersion,
                TableSet = mappings.EntityMappings[EntityType].Item1,
                PropertyToColumnMappings = mappings.EntityMappings[EntityType].Item2,
                ManyToManyMappings       = mappings.ManyToManyMappings,
                EntityName = entityName
            };
            var entityContents = templateProcessor.Process(Templates.EntityTemplate, entityHost);

            var filePath = Path.Combine(Directory, entityName + entityHost.FileExtension);

            FileGenerator.AddNewFile(filePath, entityContents);
        }
        public void Generator(EntityModelSchemaGenerator modelGenerator, TemplateProcessor templateProcessor, EdmMapping mappings)
        {
            var entityName  = EntityType.Name.RemoveSpecialChar();
            var serviceHost = new EfTextTemplateHost
            {
                EntityType              = EntityType,
                EntityContainer         = modelGenerator.EntityContainer,
                Namespace               = TemplateCommon.serviceNamespace,
                ModelsNamespace         = TemplateCommon.modelsNamespace,
                MappingNamespace        = TemplateCommon.mappingNamespace,
                RepositoryBaseNamespace = TemplateCommon.repositoryBaseNamespace,
                CoreNamespace           = TemplateCommon.coreNamespace,
                RepositoryNamespace     = TemplateCommon.repositoryNamespace,
                EntityFrameworkVersion  = TemplateCommon.entityFrameworkVersion,
                TableSet = mappings.EntityMappings[EntityType].Item1,
                PropertyToColumnMappings = mappings.EntityMappings[EntityType].Item2,
                ManyToManyMappings       = mappings.ManyToManyMappings,
                EntityName = entityName
            };
            var serviceContents = templateProcessor.Process(Templates.ServiceTemplate, serviceHost);

            var servicePath = Path.Combine(Directory, entityName + "Service" + serviceHost.FileExtension);

            FileGenerator.AddNewFile(servicePath, serviceContents);
        }
        /// <summary>
        /// 生成C#代码
        /// </summary>
        public void ReverseEngineerCodeFirst(string strCon, List <string> tableNames = null, string savePath = null)
        {
            // Load store schema
            var storeGenerator = new EntityStoreSchemaGenerator("Oracle.ManagedDataAccess.Client", strCon, "dbo");

            storeGenerator.GenerateForeignKeyProperties = true;
            var errors = storeGenerator.GenerateStoreMetadata(_storeMetadataFilters).Where(e => e.Severity == EdmSchemaErrorSeverity.Error);

            errors.HandleErrors(Strings.ReverseEngineer_SchemaError);

            // Generate default mapping
            var contextName    = "CustomDbContext";
            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(null);
            var modelsNamespace   = "EF.Models";
            var modelsDirectory   = savePath ?? Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Codes");

            if (!Directory.Exists(modelsDirectory))
            {
                Directory.CreateDirectory(modelsDirectory);
            }
            var mappingNamespace = modelsNamespace + ".Mapping";
            var mappingDirectory = Path.Combine(modelsDirectory, "Mapping");

            if (!Directory.Exists(mappingDirectory))
            {
                Directory.CreateDirectory(mappingDirectory);
            }
            var entityFrameworkVersion = new Version("6.0.0.0");

            var matchs = (tableNames ?? new List <string>()).Where(q => q.EndsWith("*")).Select(q => q.TrimEnd('*')).ToList();

            foreach (var entityType in entityTypes)
            {
                var enable = tableNames == null;
                if (tableNames != null && tableNames.Count > 0 && tableNames.Any(q => q.ToLower() == entityType.Name.ToLower()))
                {
                    enable = true;
                }
                if (!enable && matchs != null && matchs.Count > 0 && matchs.Any(q => entityType.Name.ToLower().StartsWith(q.ToLower())))
                {
                    enable = true;
                }
                if (!enable)
                {
                    continue;
                }

                // 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, ToPascal(entityType.Name) + entityHost.FileExtension);
                File.WriteAllText(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, ToPascal(entityType.Name) + "Map" + mappingHost.FileExtension);
                File.WriteAllText(mappingFilePath, mappingContents);
            }

            if (tableNames == null || tableNames.Count == 0)
            {
                // 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, ToPascal(modelGenerator.EntityContainer.Name) + contextHost.FileExtension);
                File.WriteAllText(contextFilePath, contextContents);
            }
        }
        public void ReverseEngineerCodeFirst(Project project)
        {
            Contract.Requires(project != null);

            try
            {
                // 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
                    _package.DTE2.StatusBar.Text = Strings.ReverseEngineer_GenerateClasses;
                    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)
                    {
                        // 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);
                    }

                    _package.DTE2.StatusBar.Text = Strings.ReverseEngineer_Complete;
                }
            }
            catch (Exception exception)
            {
                _package.LogError(Strings.ReverseEngineer_Error, exception);
            }
        }
示例#7
0
        public void Generator(EntityModelSchemaGenerator modelGenerator, TemplateProcessor templateProcessor, EdmMapping mappings)
        {
            var contextHost = new EfTextTemplateHost
            {
                EntityContainer        = modelGenerator.EntityContainer,
                Namespace              = TemplateCommon.modelsNamespace,
                ModelsNamespace        = TemplateCommon.modelsNamespace,
                MappingNamespace       = TemplateCommon.mappingNamespace,
                EntityFrameworkVersion = TemplateCommon.entityFrameworkVersion
            };
            var contextContents = templateProcessor.Process(Templates.ContextTemplate, contextHost);

            var contextFilePath = Path.Combine(Directory, modelGenerator.EntityContainer.Name + contextHost.FileExtension);

            FileGenerator.AddNewFile(contextFilePath, contextContents);
        }
示例#8
0
        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&quot;";
                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)
            {
            }
        }
        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 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
            {
                // 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
                    _package.DTE2.StatusBar.Text = Strings.ReverseEngineer_GenerateClasses;
                    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)
                    {
                        // 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);
                    }

                    _package.DTE2.StatusBar.Text = Strings.ReverseEngineer_Complete;
                }
            }
            catch (Exception exception)
            {
                _package.LogError(Strings.ReverseEngineer_Error, exception);
            }
        }