├── .nuget
├── NuGet.exe
├── NuGet.Config
└── NuGet.targets
├── AutoBuildEntity
├── Key.snk
├── Resources
│ ├── icon.png
│ ├── entity.gif
│ └── Package.ico
├── Model
│ ├── Constans.cs
│ ├── AutoBuildEntityContent.cs
│ ├── TemplateModel.cs
│ ├── SelectedProject.cs
│ ├── EntityXml.cs
│ ├── DbTable.cs
│ └── TableColumn.cs
├── PkgCmdID.cs
├── Common
│ ├── Helper
│ │ ├── FilesHelper.cs
│ │ ├── StringExtension.cs
│ │ ├── NVelocityHelper.cs
│ │ └── SqlHelper.cs
│ └── Extension
│ │ └── ProjectExtension.cs
├── Guids.cs
├── GlobalSuppressions.cs
├── packages.config
├── app.config
├── Properties
│ └── AssemblyInfo.cs
├── __entity.xml
├── source.extension.vsixmanifest
├── AutoBuildEntity.vsct
├── Resources.Designer.cs
├── AutoBuildEntityPackage.cs
├── Resources.resx
├── VSPackage.resx
├── Form
│ ├── MainForm.xaml
│ └── MainForm.xaml.cs
└── AutoBuildEntity.csproj
├── lib
└── Microsoft.VisualStudio.Shell.12.0.dll
├── LICENSE
├── AutoBuildEntity.sln
├── .gitattributes
├── README.md
└── .gitignore
/.nuget/NuGet.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SkyChenSky/Sikiro.BuildEntity/HEAD/.nuget/NuGet.exe
--------------------------------------------------------------------------------
/AutoBuildEntity/Key.snk:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SkyChenSky/Sikiro.BuildEntity/HEAD/AutoBuildEntity/Key.snk
--------------------------------------------------------------------------------
/AutoBuildEntity/Resources/icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SkyChenSky/Sikiro.BuildEntity/HEAD/AutoBuildEntity/Resources/icon.png
--------------------------------------------------------------------------------
/AutoBuildEntity/Resources/entity.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SkyChenSky/Sikiro.BuildEntity/HEAD/AutoBuildEntity/Resources/entity.gif
--------------------------------------------------------------------------------
/AutoBuildEntity/Resources/Package.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SkyChenSky/Sikiro.BuildEntity/HEAD/AutoBuildEntity/Resources/Package.ico
--------------------------------------------------------------------------------
/lib/Microsoft.VisualStudio.Shell.12.0.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SkyChenSky/Sikiro.BuildEntity/HEAD/lib/Microsoft.VisualStudio.Shell.12.0.dll
--------------------------------------------------------------------------------
/.nuget/NuGet.Config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/AutoBuildEntity/Model/Constans.cs:
--------------------------------------------------------------------------------
1 | namespace 陈珙.AutoBuildEntity.Model
2 | {
3 | ///
4 | /// 静态变量
5 | ///
6 | public static class Constans
7 | {
8 | public const string EntityXml = "__entity.xml";
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/AutoBuildEntity/PkgCmdID.cs:
--------------------------------------------------------------------------------
1 | // PkgCmdID.cs
2 | // MUST match PkgCmdID.h
3 | using System;
4 |
5 | namespace 陈珙.AutoBuildEntity
6 | {
7 | static class PkgCmdIDList
8 | {
9 | public const uint AutoBuildEntityCommandId = 0x100;
10 |
11 |
12 | };
13 | }
--------------------------------------------------------------------------------
/AutoBuildEntity/Common/Helper/FilesHelper.cs:
--------------------------------------------------------------------------------
1 | using System.IO;
2 |
3 | namespace 陈珙.AutoBuildEntity.Common.Helper
4 | {
5 | public static class FilesHelper
6 | {
7 | public static string WriteAndSave(string directory, string fileName, string content)
8 | {
9 | var path = Path.Combine(directory, fileName + ".cs");
10 |
11 | File.WriteAllText(path, content);
12 |
13 | return path;
14 | }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/AutoBuildEntity/Model/AutoBuildEntityContent.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.Data.SqlClient;
3 |
4 | namespace 陈珙.AutoBuildEntity.Model
5 | {
6 | ///
7 | /// 上下文
8 | ///
9 | public class AutoBuildEntityContent
10 | {
11 | public SelectedProject SelectedProject { get; set; }
12 |
13 | public EntityXml EntityXml { get; set; }
14 |
15 | public List TablesName { get; set; }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/AutoBuildEntity/Guids.cs:
--------------------------------------------------------------------------------
1 | // Guids.cs
2 | // MUST match guids.h
3 | using System;
4 |
5 | namespace 陈珙.AutoBuildEntity
6 | {
7 | static class GuidList
8 | {
9 | public const string guidAutoBuildEntityPkgString = "c095f8f8-3f87-4eac-8dc0-44939a85b2f2";
10 | public const string guidAutoBuildEntityCmdSetString = "cbe5d1f0-96e6-4ce2-90c5-860da753969c";
11 |
12 | public static readonly Guid guidAutoBuildEntityCmdSet = new Guid(guidAutoBuildEntityCmdSetString);
13 | };
14 | }
--------------------------------------------------------------------------------
/AutoBuildEntity/GlobalSuppressions.cs:
--------------------------------------------------------------------------------
1 | // This file is used by Code Analysis to maintain SuppressMessage
2 | // attributes that are applied to this project. Project-level
3 | // suppressions either have no target or are given a specific target
4 | // and scoped to a namespace, type, member, etc.
5 | //
6 | // To add a suppression to this file, right-click the message in the
7 | // Error List, point to "Suppress Message(s)", and click "In Project
8 | // Suppression File". You do not need to add suppressions to this
9 | // file manually.
10 |
11 | [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1017:MarkAssembliesWithComVisible")]
12 |
--------------------------------------------------------------------------------
/AutoBuildEntity/Common/Helper/StringExtension.cs:
--------------------------------------------------------------------------------
1 | using System.Text;
2 |
3 | namespace 陈珙.AutoBuildEntity.Common.Helper
4 | {
5 | public static class StringExtension
6 | {
7 | public static string ToCaseCamelName(this string name)
8 | {
9 | var result = new StringBuilder();
10 | if (string.IsNullOrEmpty(name))
11 | {
12 | return "";
13 | }
14 |
15 | var nameList = name.Split('_');
16 |
17 | foreach (var field in nameList)
18 | {
19 | for (var i = 0; i < field.Length; i++)
20 | {
21 | result.Append(i == 0 ? field[i].ToString().ToUpper() : field[i].ToString().ToLower());
22 | }
23 | }
24 |
25 | return result.ToString();
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/AutoBuildEntity/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/AutoBuildEntity/Model/TemplateModel.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.Linq;
3 | using 陈珙.AutoBuildEntity.Common.Helper;
4 |
5 | namespace 陈珙.AutoBuildEntity.Model
6 | {
7 | ///
8 | /// 模版实体
9 | ///
10 | public class TemplateModel
11 | {
12 | public TemplateModel(string tableName, List columns, string projectName)
13 | {
14 | TableName = tableName;
15 | Columns = columns;
16 | ProjectName = projectName;
17 | }
18 | public string TableName { get; private set; }
19 |
20 | public string TableComment => (Columns.FirstOrDefault()?.TableComment) ?? "";
21 |
22 | public string ClassName => TableName.ToCaseCamelName();
23 |
24 | public List Columns { get; private set; }
25 |
26 | public string ProjectName { get; private set; }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/AutoBuildEntity/Model/SelectedProject.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.IO;
3 | using EnvDTE;
4 |
5 | namespace 陈珙.AutoBuildEntity.Model
6 | {
7 | public class SelectedProject
8 | {
9 | public SelectedProject(string projectPath, Project projectDte, List csFilesName)
10 | {
11 | ProjectPath = projectPath;
12 | ProjectDte = projectDte;
13 | CsFilesName = csFilesName;
14 | }
15 | public string ProjectPath { get; }
16 |
17 | public string ProjectName => Path.GetFileNameWithoutExtension(ProjectPath);
18 |
19 | public string ProjectDirectoryName => Path.GetDirectoryName(ProjectPath);
20 |
21 | public Project ProjectDte { get; }
22 |
23 | public string EntityXmlPath => Path.Combine(ProjectDirectoryName, Constans.EntityXml);
24 |
25 | public List CsFilesName { get; }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/AutoBuildEntity/app.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 陈珙
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/AutoBuildEntity.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 15
4 | VisualStudioVersion = 15.0.27130.2020
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoBuildEntity", "AutoBuildEntity\AutoBuildEntity.csproj", "{D66A2359-0BD8-4BA5-AF0C-A31BD7CDC1BC}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {D66A2359-0BD8-4BA5-AF0C-A31BD7CDC1BC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {D66A2359-0BD8-4BA5-AF0C-A31BD7CDC1BC}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {D66A2359-0BD8-4BA5-AF0C-A31BD7CDC1BC}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {D66A2359-0BD8-4BA5-AF0C-A31BD7CDC1BC}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | GlobalSection(ExtensibilityGlobals) = postSolution
23 | SolutionGuid = {7741C249-CA51-4AE2-903A-CE4A2D33BAF5}
24 | EndGlobalSection
25 | EndGlobal
26 |
--------------------------------------------------------------------------------
/AutoBuildEntity/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Reflection;
3 | using System.Resources;
4 | using System.Runtime.CompilerServices;
5 | using System.Runtime.InteropServices;
6 |
7 | // General Information about an assembly is controlled through the following
8 | // set of attributes. Change these attribute values to modify the information
9 | // associated with an assembly.
10 | [assembly: AssemblyTitle("AutoBuildEntity")]
11 | [assembly: AssemblyDescription("")]
12 | [assembly: AssemblyConfiguration("")]
13 | [assembly: AssemblyCompany("陈珙")]
14 | [assembly: AssemblyProduct("AutoBuildEntity")]
15 | [assembly: AssemblyCopyright("")]
16 | [assembly: AssemblyTrademark("")]
17 | [assembly: AssemblyCulture("")]
18 | [assembly: ComVisible(false)]
19 | [assembly: CLSCompliant(false)]
20 | [assembly: NeutralResourcesLanguage("en-US")]
21 |
22 | // Version information for an assembly consists of the following four values:
23 | //
24 | // Major Version
25 | // Minor Version
26 | // Build Number
27 | // Revision
28 | //
29 | // You can specify all the values or you can default the Revision and Build Numbers
30 | // by using the '*' as shown below:
31 |
32 | [assembly: AssemblyVersion("1.0.0.0")]
33 | [assembly: AssemblyFileVersion("1.0.0.0")]
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/AutoBuildEntity/Common/Helper/NVelocityHelper.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using NVelocity;
5 | using NVelocity.App;
6 | using NVelocity.Runtime;
7 |
8 | namespace 陈珙.AutoBuildEntity.Common.Helper
9 | {
10 | public static class NVelocityHelper
11 | {
12 | ///
13 | /// 初始化模板引擎
14 | ///
15 | public static string ProcessTemplate(string template, Dictionary param)
16 | {
17 | var templateEngine = new VelocityEngine();
18 | templateEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");
19 |
20 | templateEngine.SetProperty(RuntimeConstants.INPUT_ENCODING, "utf-8");
21 | templateEngine.SetProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8");
22 |
23 | templateEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, AppDomain.CurrentDomain.BaseDirectory);
24 |
25 |
26 | var context = new VelocityContext();
27 | foreach (var item in param)
28 | {
29 | context.Put(item.Key, item.Value);
30 | }
31 |
32 | templateEngine.Init();
33 |
34 |
35 | var writer = new StringWriter();
36 | templateEngine.Evaluate(context, writer, "mystring", template);
37 |
38 | return writer.GetStringBuilder().ToString();
39 | }
40 |
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/AutoBuildEntity/__entity.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
6 |
7 |
8 | mysql
9 |
10 |
11 |
27 | #if($c.Remark != "")
28 | /// $c.Remark
29 | #else
30 | /// $c.Name
31 | #end
32 | ///
33 | #if($c.IsKey)
34 | [Key]
35 | #end
36 | #if($c.IsIdentity)
37 | [AutoIncrement]
38 | #elseif($c.CSharpType == "int")
39 | [NonAutoIncrementAttribute]
40 | #end
41 | #if(!$c.IsNullable)
42 | [Required]
43 | #end
44 | #if($c.CSharpType == "string" && $c.Length != -1)
45 | [StringLength($c.Length)]
46 | #end
47 | #if($c.Remark != "")
48 | [Display(Name="$c.Remark")]
49 | #else
50 | [Display(Name="$c.Name")]
51 | #end
52 | [Column("$c.Name")]
53 | public $c.CSharpType $c.PropertyName{ get; set; }
54 | #end
55 | }
56 | }
57 | ]]>
58 |
59 |
--------------------------------------------------------------------------------
/AutoBuildEntity/Model/EntityXml.cs:
--------------------------------------------------------------------------------
1 | using System.Xml;
2 |
3 | namespace 陈珙.AutoBuildEntity.Model
4 | {
5 | ///
6 | /// 配置文件
7 | ///
8 | public class EntityXml
9 | {
10 | private readonly string _path;
11 |
12 | public EntityXml(string path)
13 | {
14 | _path = path;
15 | }
16 |
17 | public string ConnString { get; private set; }
18 |
19 | public string EntityTemplate { get; private set; }
20 |
21 | public string Type { get; private set; }
22 |
23 | ///
24 | /// 读取_entity.xml
25 | ///
26 | ///
27 | public EntityXml Load()
28 | {
29 | var xml = new XmlDocument();
30 | xml.Load(_path);
31 |
32 | var autoEntityNode = xml.SelectSingleNode("AutoEntity");
33 | if (autoEntityNode == null)
34 | return this;
35 |
36 | var connStringNode = autoEntityNode.SelectSingleNode("ConnString");
37 | if (connStringNode != null)
38 | ConnString = connStringNode.InnerText;
39 |
40 | var templatesNodes = autoEntityNode.SelectSingleNode("Template");
41 | if (templatesNodes != null)
42 | EntityTemplate = templatesNodes.InnerText; ;
43 |
44 | var type = autoEntityNode.SelectSingleNode("Type");
45 | if (type != null)
46 | Type = type.InnerText.Trim().Replace("\r\n", ""); ;
47 | Type = Type ?? "mysql";
48 |
49 | return this;
50 | }
51 | }
52 | }
--------------------------------------------------------------------------------
/AutoBuildEntity/source.extension.vsixmanifest:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | AutoBuildEntity
6 | 自动生成实体工具
7 | https://github.com/SkyChenSky/AutoBuildEntity
8 | Resources\Package.ico
9 | Resources\Package.ico
10 | DataBase Entity
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/AutoBuildEntity/Model/DbTable.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.Data;
3 | using System.Linq;
4 | using 陈珙.AutoBuildEntity.Common.Helper;
5 |
6 | namespace 陈珙.AutoBuildEntity.Model
7 | {
8 | ///
9 | /// 物理表
10 | ///
11 | public class DbTable
12 | {
13 | public string TableName { get; }
14 |
15 | public List Columns { get; set; }
16 |
17 | private readonly string _conn;
18 |
19 | public DbTable(string conn)
20 | {
21 | _conn = conn;
22 | }
23 |
24 | public DbTable(string tableName, List columns)
25 | {
26 | TableName = tableName;
27 | Columns = columns;
28 | }
29 |
30 | public List QueryMssqlTablesName()
31 | {
32 | var result = SqlHelper.MssqlQuery(_conn, @"SELECT name FROM sysobjects WHERE xtype IN ( 'u','v' ); ");
33 |
34 | return (from DataRow row in result.Rows select row[0].ToString()).ToList();
35 | }
36 |
37 | public List QueryMysqlTablesName()
38 | {
39 | var result = SqlHelper.MysqlQuery(_conn, @"show tables; ");
40 |
41 | return (from DataRow row in result.Rows select row[0].ToString()).ToList();
42 | }
43 |
44 |
45 | public List GetTables(List tablesName, string sqlType)
46 | {
47 | if (!tablesName.Any())
48 | return new List();
49 |
50 | var t = new TableColumn(_conn, sqlType);
51 |
52 | var columns = t.GetColumn(tablesName);
53 |
54 | return columns.GroupBy(a => a.TableName).Select(a => new DbTable(a.Key, a.ToList())).ToList();
55 | }
56 |
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/AutoBuildEntity/AutoBuildEntity.vsct:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
12 |
13 |
14 |
15 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/AutoBuildEntity/Resources.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // 此代码由工具生成。
4 | // 运行时版本:4.0.30319.42000
5 | //
6 | // 对此文件的更改可能会导致不正确的行为,并且如果
7 | // 重新生成代码,这些更改将会丢失。
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace 陈珙.AutoBuildEntity {
12 | using System;
13 |
14 |
15 | ///
16 | /// 一个强类型的资源类,用于查找本地化的字符串等。
17 | ///
18 | // 此类是由 StronglyTypedResourceBuilder
19 | // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
20 | // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
21 | // (以 /str 作为命令选项),或重新生成 VS 项目。
22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")]
23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
25 | internal class Resources {
26 |
27 | private static global::System.Resources.ResourceManager resourceMan;
28 |
29 | private static global::System.Globalization.CultureInfo resourceCulture;
30 |
31 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
32 | internal Resources() {
33 | }
34 |
35 | ///
36 | /// 返回此类使用的缓存的 ResourceManager 实例。
37 | ///
38 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
39 | internal static global::System.Resources.ResourceManager ResourceManager {
40 | get {
41 | if (object.ReferenceEquals(resourceMan, null)) {
42 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("陈珙.AutoBuildEntity.Resources", typeof(Resources).Assembly);
43 | resourceMan = temp;
44 | }
45 | return resourceMan;
46 | }
47 | }
48 |
49 | ///
50 | /// 使用此强类型资源类,为所有资源查找
51 | /// 重写当前线程的 CurrentUICulture 属性。
52 | ///
53 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
54 | internal static global::System.Globalization.CultureInfo Culture {
55 | get {
56 | return resourceCulture;
57 | }
58 | set {
59 | resourceCulture = value;
60 | }
61 | }
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # 实体生成插件
2 | 基于visual studio sdk开发的方便、直观的实体生成工具。
3 |
4 | ## 项目博客地址
5 | http://www.cnblogs.com/skychen1218/p/6848128.html
6 |
7 | ## 更新历史
8 | |时间|内容|
9 | | ------- | ------|
10 | |2019.11.6|修复批量更新与添加、更新后项目自动重新加载文件、mysql数据库的映射|
11 | |2020.1.8|通过配置文件区分mssql和mysql|
12 | |2020.5.24|修复引用问题、全选的问题、2019兼容问题|
13 |
14 | ## 支持版本
15 | visual studio 2013、2015、2017、2019
16 |
17 |
18 | ## 怎么使用
19 |
20 | ### 配置结构
21 |
22 | ```xml
23 |
24 |
25 |
28 |
29 |
30 | mysql
31 |
32 |
33 |
43 | /// $entity.TableComment
44 | ///
45 | [Table("$entity.TableName")]
46 | public class $entity.ClassName
47 | {
48 | #foreach($c in $entity.Columns)
49 |
50 | ///
51 | #if($c.Remark != "")
52 | /// $c.Remark
53 | #else
54 | /// $c.Name
55 | #end
56 | ///
57 | #if($c.IsIdentity)
58 | [AutoIncrement]
59 | #elseif($c.CSharpType == "int")
60 | [NonAutoIncrementAttribute]
61 | #end
62 | [Column("$c.Name")]
63 | public $c.CSharpType $c.PropertyName{ get; set; }
64 | #end
65 | }
66 | }
67 | ]]>
68 |
69 |
70 | ```
71 |
72 | |数据库名称|文件内使用|
73 | | ------- | ------|
74 | |sql server|mssql|
75 | |mysql|mysql|
76 |
77 | ### 效果图
78 | 
79 |
80 | ### 安装
81 |
82 | 下载代码编译完成后,到bin目录下找到AutoBuildEntity.vsix双击安装
83 |
84 | ### 模板配置
85 |
86 | 配置文件命名约定为__entity.xml,可以参考源码目录下的文件《__entity.xml》。结构主要区分为数据库链接配置与实体模板配置,因为引入组件[NVelocity](https://github.com/castleproject/NVelocity/blob/master/docs/nvelocity.md),如果需要对模板扩展可以查看具体文档。
87 |
88 | ### 实际使用
89 | 先把上面的配置放到项目-选中项目-右键-点击‘自动生成实体工具’-选择新增(更新、删除)数据源-确认。很简单、很直观
90 |
91 |
92 | ## 可能遇到的问题
93 |
94 | ### 查找VS的界面guid与cmdid
95 | 在VS的【扩展与更新】搜索并安装Extensibility Tools,然后在vs【视图】-【 Enable VSIP Logging】点击并重启后,就可以用ctrl+shirt+右键点击需要查的界面,就可以弹出需要的信息,我测试过vs2017可用。
96 |
97 | ### 无法调试
98 | 选中项目-右键-属性-调试
99 |
100 | - 启动配置外部程序(按照你的VS版本选择)
101 | ```
102 | C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\devenv.exe
103 | ```
104 |
105 | - 命令行参数
106 | ```
107 | /rootsuffix Exp
108 | ```
109 |
110 | ### 制作icon
111 | http://iconfont.cn/search/index
112 |
113 | http://www.easyicon.net/covert/
114 |
115 | ### visual studio sdk包下载(如果你无法编译通过)
116 | - 小于2015版本
117 | - https://marketplace.visualstudio.com/items?itemName=VisualStudioProductTeam.MicrosoftVisualStudio2013SDK
118 | - 大于2015版本
119 | - 工具-获取工具和功能-勾选-Visual Studio 扩展开发
120 |
121 |
122 | ### 微软开发文档
123 | https://docs.microsoft.com/zh-cn/dotnet/api/envdte.dte?redirectedfrom=MSDN&view=visualstudiosdk-2017
124 |
125 |
126 | ## 标签
127 | visual studio sdk vsix 插件 工具
128 |
--------------------------------------------------------------------------------
/AutoBuildEntity/Common/Extension/ProjectExtension.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Linq;
5 | using System.Runtime.InteropServices;
6 | using EnvDTE;
7 | using Microsoft.VisualStudio;
8 | using Microsoft.VisualStudio.Shell.Interop;
9 | using 陈珙.AutoBuildEntity.Model;
10 |
11 | namespace 陈珙.AutoBuildEntity.Common.Extension
12 | {
13 | public static class ProjectExtension
14 | {
15 | ///
16 | /// 获取选中项目的信息
17 | ///
18 | ///
19 | ///
20 | public static SelectedProject GetSelectedProjectInfo(this DTE dte)
21 | {
22 | var selectedItems = dte.SelectedItems;
23 |
24 | var projectName = (from SelectedItem item in selectedItems select item.Name).ToList();
25 |
26 | if (!selectedItems.MultiSelect && selectedItems.Count == 1)
27 | {
28 | var selectProject = selectedItems.Item(projectName.First());
29 |
30 | var projectFileList = (from ProjectItem projectItem in selectProject.Project.ProjectItems
31 | where projectItem.Name.EndsWith(".cs")
32 | select Path.GetFileNameWithoutExtension(projectItem.Name)).ToList();
33 |
34 | return new SelectedProject(selectProject.Project.FullName, selectProject.Project, projectFileList);
35 | }
36 |
37 | return null;
38 | }
39 |
40 | ///
41 | /// 添加项目项
42 | ///
43 | ///
44 | ///
45 | public static void AddFilesToProject(this Project projectDte, List files)
46 | {
47 | foreach (string file in files)
48 | {
49 | projectDte.ProjectItems.AddFromFile(file);
50 | }
51 |
52 | //if (files.Any())
53 | // projectDte.Save();
54 | }
55 |
56 | ///
57 | /// 排除项目项
58 | ///
59 | ///
60 | ///
61 | public static void RemoveFilesFromProject(this Project projectDte, List files)
62 | {
63 | foreach (string file in files)
64 | {
65 | projectDte.ProjectItems.Item(Path.GetFileName(file)).Remove();
66 | }
67 | }
68 |
69 | ///
70 | /// 警告提示框
71 | ///
72 | ///
73 | ///
74 | public static void ShowMessageBox(this IVsUIShell uiShell, string msg)
75 | {
76 | var clsid = Guid.Empty;
77 | int result;
78 | ErrorHandler.ThrowOnFailure(uiShell.ShowMessageBox(
79 | 0,
80 | ref clsid,
81 | "提示",
82 | msg,
83 | string.Empty,
84 | 0,
85 | OLEMSGBUTTON.OLEMSGBUTTON_OK,
86 | OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST,
87 | OLEMSGICON.OLEMSGICON_INFO,
88 | 0,
89 | out result));
90 | }
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/AutoBuildEntity/AutoBuildEntityPackage.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Runtime.InteropServices;
4 | using System.ComponentModel.Design;
5 | using EnvDTE;
6 | using Microsoft.VisualStudio.Shell.Interop;
7 | using Microsoft.VisualStudio.Shell;
8 | using 陈珙.AutoBuildEntity.Common.Extension;
9 | using 陈珙.AutoBuildEntity.Form;
10 | using 陈珙.AutoBuildEntity.Model;
11 |
12 | namespace 陈珙.AutoBuildEntity
13 | {
14 | [PackageRegistration(UseManagedResourcesOnly = true)]
15 | [InstalledProductRegistration("#110", "#112", "1.0", IconResourceID = 400)]
16 | [ProvideMenuResource("Menus.ctmenu", 1)]
17 | [Guid(GuidList.guidAutoBuildEntityPkgString)]
18 | public sealed class AutoBuildEntityPackage : Package
19 | {
20 | #region 初始化
21 | protected override void Initialize()
22 | {
23 | base.Initialize();
24 |
25 | var mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
26 | if (null != mcs)
27 | {
28 | var menuCommandId = new CommandID(GuidList.guidAutoBuildEntityCmdSet, (int)PkgCmdIDList.AutoBuildEntityCommandId);
29 |
30 | var menuItem = new OleMenuCommand(AutoBuildEntityEvent, menuCommandId);
31 | mcs.AddCommand(menuItem);
32 | }
33 | }
34 | #endregion
35 |
36 | ///
37 | /// 按钮事件
38 | ///
39 | ///
40 | ///
41 | private void AutoBuildEntityEvent(object sender, EventArgs e)
42 | {
43 | var uiShell = (IVsUIShell)GetService(typeof(SVsUIShell));
44 |
45 | //获取选中项目信息
46 | var autoBuildEntityContent = new AutoBuildEntityContent { SelectedProject = GetSelectedProject() };
47 | if (autoBuildEntityContent.SelectedProject == null)
48 | {
49 | uiShell.ShowMessageBox("获取项目信息失败");
50 | return;
51 | }
52 |
53 | //读取选中项目下的配置信息
54 | var entityXmlModel = new EntityXml(autoBuildEntityContent.SelectedProject.EntityXmlPath);
55 | entityXmlModel.Load();
56 | autoBuildEntityContent.EntityXml = entityXmlModel;
57 |
58 | try
59 | {
60 | //读取表集合
61 | autoBuildEntityContent.TablesName = GetTables(entityXmlModel.ConnString, entityXmlModel.Type);
62 | }
63 | catch (Exception ex)
64 | {
65 | uiShell.ShowMessageBox($"数据库访问异常:{ex.Message}");
66 | return;
67 | }
68 |
69 | new MainForm(autoBuildEntityContent, entityXmlModel.Type).ShowDialog();
70 | }
71 |
72 | ///
73 | /// 获取选中的项目所有信息
74 | ///
75 | ///
76 | private SelectedProject GetSelectedProject()
77 | {
78 | var dte = (DTE)GetService(typeof(SDTE));
79 |
80 | //获取选中项目信息
81 | var projectInfo = dte.GetSelectedProjectInfo();
82 |
83 | return projectInfo;
84 | }
85 |
86 | ///
87 | /// 获取物理表
88 | ///
89 | ///
90 | ///
91 | private List GetTables(string sqlstr, string sqlType)
92 | {
93 | var dbTable = new DbTable(sqlstr);
94 |
95 | switch (sqlType)
96 | {
97 | case "mysql":
98 | return dbTable.QueryMysqlTablesName();
99 | case "mssql":
100 | return dbTable.QueryMssqlTablesName();
101 | default: throw new Exception("未知类型");
102 | }
103 | }
104 | }
105 | }
106 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # User-specific files
5 | *.suo
6 | *.user
7 | *.sln.docstates
8 |
9 | # Build results
10 | [Dd]ebug/
11 | [Dd]ebugPublic/
12 | [Rr]elease/
13 | x64/
14 | build/
15 | bld/
16 | [Bb]in/
17 | [Oo]bj/
18 |
19 | # Roslyn cache directories
20 | *.ide/
21 |
22 | # MSTest test Results
23 | [Tt]est[Rr]esult*/
24 | [Bb]uild[Ll]og.*
25 |
26 | #NUNIT
27 | *.VisualState.xml
28 | TestResult.xml
29 |
30 | # Build Results of an ATL Project
31 | [Dd]ebugPS/
32 | [Rr]eleasePS/
33 | dlldata.c
34 |
35 | *_i.c
36 | *_p.c
37 | *_i.h
38 | *.ilk
39 | *.meta
40 | *.obj
41 | *.pch
42 | *.pdb
43 | *.pgc
44 | *.pgd
45 | *.rsp
46 | *.sbr
47 | *.tlb
48 | *.tli
49 | *.tlh
50 | *.tmp
51 | *.tmp_proj
52 | *.log
53 | *.vspscc
54 | *.vssscc
55 | .builds
56 | *.pidb
57 | *.svclog
58 | *.scc
59 |
60 | # Chutzpah Test files
61 | _Chutzpah*
62 |
63 | # Visual C++ cache files
64 | ipch/
65 | *.aps
66 | *.ncb
67 | *.opensdf
68 | *.sdf
69 | *.cachefile
70 |
71 | # Visual Studio profiler
72 | *.psess
73 | *.vsp
74 | *.vspx
75 |
76 | # TFS 2012 Local Workspace
77 | $tf/
78 |
79 | # Guidance Automation Toolkit
80 | *.gpState
81 |
82 | # ReSharper is a .NET coding add-in
83 | _ReSharper*/
84 | *.[Rr]e[Ss]harper
85 | *.DotSettings.user
86 |
87 | # JustCode is a .NET coding addin-in
88 | .JustCode
89 |
90 | # TeamCity is a build add-in
91 | _TeamCity*
92 |
93 | # DotCover is a Code Coverage Tool
94 | *.dotCover
95 |
96 | # NCrunch
97 | _NCrunch_*
98 | .*crunch*.local.xml
99 |
100 | # MightyMoose
101 | *.mm.*
102 | AutoTest.Net/
103 |
104 | # Web workbench (sass)
105 | .sass-cache/
106 |
107 | # Installshield output folder
108 | [Ee]xpress/
109 |
110 | # DocProject is a documentation generator add-in
111 | DocProject/buildhelp/
112 | DocProject/Help/*.HxT
113 | DocProject/Help/*.HxC
114 | DocProject/Help/*.hhc
115 | DocProject/Help/*.hhk
116 | DocProject/Help/*.hhp
117 | DocProject/Help/Html2
118 | DocProject/Help/html
119 |
120 | # Click-Once directory
121 | publish/
122 |
123 | # Publish Web Output
124 | *.[Pp]ublish.xml
125 | *.azurePubxml
126 | ## TODO: Comment the next line if you want to checkin your
127 | ## web deploy settings but do note that will include unencrypted
128 | ## passwords
129 | #*.pubxml
130 |
131 | # NuGet Packages Directory
132 | packages/*
133 | ## TODO: If the tool you use requires repositories.config
134 | ## uncomment the next line
135 | #!packages/repositories.config
136 |
137 | # Enable "build/" folder in the NuGet Packages folder since
138 | # NuGet packages use it for MSBuild targets.
139 | # This line needs to be after the ignore of the build folder
140 | # (and the packages folder if the line above has been uncommented)
141 | !packages/build/
142 |
143 | # Windows Azure Build Output
144 | csx/
145 | *.build.csdef
146 |
147 | # Windows Store app package directory
148 | AppPackages/
149 |
150 | # Others
151 | sql/
152 | *.Cache
153 | ClientBin/
154 | [Ss]tyle[Cc]op.*
155 | ~$*
156 | *~
157 | *.dbmdl
158 | *.dbproj.schemaview
159 | *.pfx
160 | *.publishsettings
161 | node_modules/
162 |
163 | # RIA/Silverlight projects
164 | Generated_Code/
165 |
166 | # Backup & report files from converting an old project file
167 | # to a newer Visual Studio version. Backup files are not needed,
168 | # because we have git ;-)
169 | _UpgradeReport_Files/
170 | Backup*/
171 | UpgradeLog*.XML
172 | UpgradeLog*.htm
173 |
174 | # SQL Server files
175 | *.mdf
176 | *.ldf
177 |
178 | # Business Intelligence projects
179 | *.rdl.data
180 | *.bim.layout
181 | *.bim_*.settings
182 |
183 | # Microsoft Fakes
184 | FakesAssemblies/
185 |
186 | # LightSwitch generated files
187 | GeneratedArtifacts/
188 | _Pvt_Extensions/
189 | ModelManifest.xml
190 | /.vs/AutoBuildEntity/v15/Server/sqlite3
191 | /.nuget
192 | /.vs/AutoBuildEntity/v16/Server/sqlite3
193 |
--------------------------------------------------------------------------------
/AutoBuildEntity/Common/Helper/SqlHelper.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Data;
3 | using System.Data.SqlClient;
4 | using MySql.Data.MySqlClient;
5 |
6 | namespace 陈珙.AutoBuildEntity.Common.Helper
7 | {
8 | public static class SqlHelper
9 | {
10 | public static string DataBase { get; set; }
11 |
12 | public static DataTable MssqlQuery(string connStr, string sql, SqlParameter[] sqlParameter = null)
13 | {
14 | var dt = new DataTable();
15 | using (var conn = new SqlConnection(connStr))
16 | {
17 | conn.Open();
18 |
19 | DataBase = conn.Database;
20 |
21 | var cmd = conn.CreateCommand();
22 |
23 | cmd.CommandText = sql;
24 |
25 | if (sqlParameter != null)
26 | cmd.Parameters.AddRange(sqlParameter);
27 |
28 | var dr = cmd.ExecuteReader();
29 |
30 | dt.Load(dr);
31 | }
32 |
33 | return dt;
34 | }
35 |
36 | public static DataTable MysqlQuery(string connStr, string sql)
37 | {
38 | var dt = new DataTable();
39 | using (var conn = new MySqlConnection(connStr))
40 | {
41 | conn.Open();
42 |
43 | DataBase = conn.Database;
44 |
45 | var cmd = conn.CreateCommand();
46 |
47 | cmd.CommandText = sql;
48 |
49 | var dr = cmd.ExecuteReader();
50 |
51 | dt.Load(dr);
52 | }
53 |
54 | return dt;
55 | }
56 |
57 | public static string MapMysqlToCsharpType(string dbtype, bool isNullable)
58 | {
59 | if (string.IsNullOrEmpty(dbtype)) return dbtype;
60 | dbtype = dbtype.ToLower();
61 | string csharpType;
62 | switch (dbtype)
63 | {
64 | case "date":
65 | case "datetime":
66 | case "datetime2":
67 | case "smalldatetime": csharpType = isNullable ? "DateTime?" : "DateTime"; break;
68 | case "nchar":
69 | case "ntext":
70 | case "char":
71 | case "varchar":
72 | case "xml":
73 | case "text":
74 | case "longtext":
75 | case "nvarchar": csharpType = "string"; break;
76 | case "decimal":
77 | case "money":
78 | case "numeric":
79 | case "smallmoney": csharpType = isNullable ? "decimal?" : "decimal"; break;
80 | case "timestamp":
81 | case "varbinary":
82 | case "binary":
83 | case "image": csharpType = "byte[]"; break;
84 | case "tinyint": csharpType = isNullable ? "byte?" : "byte"; break;
85 | case "bigint": csharpType = isNullable ? "long?" : "long"; break;
86 | case "bit": csharpType = isNullable ? "bool?" : "bool"; break;
87 | case "datetimeoffset": csharpType = isNullable ? "DateTimeOffset?" : "DateTimeOffset"; break;
88 | case "double":
89 | case "real":
90 | case "float": csharpType = isNullable ? "double?" : "double"; break;
91 | case "int": csharpType = isNullable ? "int?" : "int"; break;
92 | case "smallint": csharpType = isNullable ? "short?" : "short"; break;
93 | case "sql_variant":
94 | case "sysname": csharpType = "object"; break;
95 | case "time": csharpType = "TimeSpan"; break;
96 | case "uniqueidentifier": csharpType = "Guid"; break;
97 | default: csharpType = "object"; break;
98 | }
99 | return csharpType;
100 | }
101 | }
102 | }
103 |
--------------------------------------------------------------------------------
/AutoBuildEntity/Resources.resx:
--------------------------------------------------------------------------------
1 |
2 |
11 |
12 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 | text/microsoft-resx
119 |
120 |
121 | 2.0
122 |
123 |
124 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
125 |
126 |
127 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
128 |
129 |
--------------------------------------------------------------------------------
/AutoBuildEntity/Model/TableColumn.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Data;
4 | using System.Data.SqlClient;
5 | using System.Linq;
6 | using 陈珙.AutoBuildEntity.Common.Helper;
7 |
8 | namespace 陈珙.AutoBuildEntity.Model
9 | {
10 | ///
11 | /// 物理表的列信息
12 | ///
13 | public class TableColumn
14 | {
15 | private readonly string _connStr;
16 | private readonly string _sqltype;
17 | public TableColumn()
18 | {
19 |
20 | }
21 | public TableColumn(string connStr, string sqltype)
22 | {
23 | _connStr = connStr;
24 | _sqltype = sqltype;
25 | }
26 |
27 | public string TableName { get; private set; }
28 |
29 | public string TableComment { get; private set; }
30 |
31 | public string Name { get; private set; }
32 |
33 | public string PropertyName => Name.ToCaseCamelName();
34 |
35 | public string Remark { get; private set; }
36 |
37 | public string Type { get; private set; }
38 |
39 | public long Length { get; private set; }
40 |
41 | public bool IsIdentity { get; private set; }
42 |
43 | public bool IsKey { get; private set; }
44 |
45 | public bool IsNullable { get; private set; }
46 |
47 | public string CSharpType => SqlHelper.MapMysqlToCsharpType(Type, IsNullable);
48 |
49 | public List GetColumn(List tablesName)
50 | {
51 | List list;
52 | switch (_sqltype)
53 | {
54 | case "mysql":
55 | list = GetMySqlDbColumn(tablesName); break;
56 | case "mssql":
57 | list = GetMssqlColumn(tablesName); break;
58 | default: throw new Exception("无法识别");
59 | }
60 |
61 | return list;
62 | }
63 |
64 | ///
65 | /// 查询列信息
66 | ///
67 | ///
68 | ///
69 | private List GetMssqlColumn(List tablesName)
70 | {
71 | #region 表结构
72 |
73 | var paramKey = string.Join(",", tablesName.Select((a, index) => "@p" + index));
74 | var paramVal = tablesName.Select((a, index) => new SqlParameter("@p" + index, a)).ToArray();
75 | var sql = $@"SELECT obj.name AS tablename ,
76 | col.name ,
77 | ISNULL(ep.[value], '') remark ,
78 | t.name AS type ,
79 | col.length ,
80 | COLUMNPROPERTY(col.id, col.name, 'IsIdentity') AS isidentity ,
81 | CASE WHEN EXISTS ( SELECT 1
82 | FROM dbo.sysindexes si
83 | INNER JOIN dbo.sysindexkeys sik ON si.id = sik.id
84 | AND si.indid = sik.indid
85 | INNER JOIN dbo.syscolumns sc ON sc.id = sik.id
86 | AND sc.colid = sik.colid
87 | INNER JOIN dbo.sysobjects so ON so.name = si.name
88 | AND so.xtype = 'PK'
89 | WHERE sc.id = col.id
90 | AND sc.colid = col.colid ) THEN 1
91 | ELSE 0
92 | END AS iskey ,
93 | col.isnullable
94 | FROM dbo.syscolumns col
95 | LEFT JOIN dbo.systypes t ON col.xtype = t.xusertype
96 | INNER JOIN dbo.sysobjects obj ON col.id = obj.id
97 | AND obj.xtype IN ( 'U', 'v' )
98 | AND obj.status >= 0
99 | LEFT JOIN dbo.syscomments comm ON col.cdefault = comm.id
100 | LEFT JOIN sys.extended_properties ep ON col.id = ep.major_id
101 | AND col.colid = ep.minor_id
102 | AND ep.name = 'MS_Description'
103 | LEFT JOIN sys.extended_properties epTwo ON obj.id = epTwo.major_id
104 | AND epTwo.minor_id = 0
105 | AND epTwo.name = 'MS_Description'
106 | WHERE obj.name IN ({paramKey});";
107 |
108 | #endregion
109 |
110 | var result = SqlHelper.MssqlQuery(_connStr, sql, paramVal);
111 |
112 | return (from DataRow row in result.Rows
113 | select new TableColumn
114 | {
115 | IsIdentity = Convert.ToBoolean(row["isidentity"]),
116 | IsKey = Convert.ToBoolean(row["iskey"]),
117 | IsNullable = Convert.ToBoolean(row["isnullable"]),
118 | Length = Convert.ToInt64(row["length"]),
119 | Name = row["name"].ToString(),
120 | Remark = row["remark"].ToString(),
121 | TableName = row["tablename"].ToString(),
122 | Type = row["type"].ToString()
123 | }).ToList();
124 | }
125 |
126 | private List GetMySqlDbColumn(List tablesName)
127 | {
128 | #region 表结构
129 | var sql = $@"SELECT
130 | *,
131 | (SELECT
132 | table_comment
133 | FROM
134 | information_schema.tables
135 | WHERE
136 | table_name = tablename
137 | LIMIT 1) tableComment
138 | FROM
139 | (SELECT
140 | TABLE_NAME tablename,
141 | COLUMN_NAME name,
142 | COLUMN_comment remark,
143 | data_type type,
144 | CASE
145 | WHEN CHARACTER_MAXIMUM_LENGTH IS NULL THEN 0
146 | ELSE CHARACTER_MAXIMUM_LENGTH
147 | END length,
148 | CASE
149 | WHEN COLUMN_keY = 'PRI' THEN 1
150 | ELSE 0
151 | END iskey,
152 | CASE
153 | WHEN IS_NULLABLE = 'NO' THEN 0
154 | ELSE 1
155 | END isnullable,
156 | 0 isidentity
157 | FROM
158 | INFORMATION_SCHEMA.COLUMNS
159 | WHERE
160 | TABLE_NAME IN ('{string.Join("','", tablesName).TrimEnd(',')}') AND Table_schema = '{SqlHelper.DataBase}') t";
161 | #endregion
162 |
163 | var result = SqlHelper.MysqlQuery(_connStr, sql);
164 |
165 | return (from DataRow row in result.Rows
166 | select new TableColumn
167 | {
168 | IsIdentity = Convert.ToBoolean(row["isidentity"]),
169 | IsKey = Convert.ToBoolean(row["iskey"]),
170 | IsNullable = Convert.ToBoolean(row["isnullable"]),
171 | Length = Convert.ToInt64(row["length"]),
172 | Name = row["name"].ToString(),
173 | Remark = row["remark"].ToString(),
174 | TableName = row["tablename"].ToString(),
175 | Type = row["type"].ToString(),
176 | TableComment = row["TableComment"].ToString(),
177 | }).ToList();
178 | }
179 | }
180 | }
181 |
--------------------------------------------------------------------------------
/AutoBuildEntity/VSPackage.resx:
--------------------------------------------------------------------------------
1 |
2 |
12 |
13 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 | text/microsoft-resx
120 |
121 |
122 | 2.0
123 |
124 |
125 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
126 |
127 |
128 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
129 |
130 |
131 |
132 | AutoBuildEntity
133 |
134 |
135 | 自动生成实体工具
136 |
137 |
138 | Resources\Package.ico;System.Drawing.Icon, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
139 |
140 |
--------------------------------------------------------------------------------
/AutoBuildEntity/Form/MainForm.xaml:
--------------------------------------------------------------------------------
1 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
--------------------------------------------------------------------------------
/.nuget/NuGet.targets:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | $(MSBuildProjectDirectory)\..\
5 |
6 |
7 | false
8 |
9 |
10 | false
11 |
12 |
13 | true
14 |
15 |
16 | false
17 |
18 |
19 |
20 |
21 |
22 |
26 |
27 |
28 |
29 |
30 | $([System.IO.Path]::Combine($(SolutionDir), ".nuget"))
31 |
32 |
33 |
34 |
35 | $(SolutionDir).nuget
36 |
37 |
38 |
39 | $(MSBuildProjectDirectory)\packages.$(MSBuildProjectName.Replace(' ', '_')).config
40 | $(MSBuildProjectDirectory)\packages.$(MSBuildProjectName).config
41 |
42 |
43 |
44 | $(MSBuildProjectDirectory)\packages.config
45 | $(PackagesProjectConfig)
46 |
47 |
48 |
49 |
50 | $(NuGetToolsPath)\NuGet.exe
51 | @(PackageSource)
52 |
53 | "$(NuGetExePath)"
54 | mono --runtime=v4.0.30319 "$(NuGetExePath)"
55 |
56 | $(TargetDir.Trim('\\'))
57 |
58 | -RequireConsent
59 | -NonInteractive
60 |
61 | "$(SolutionDir) "
62 | "$(SolutionDir)"
63 |
64 |
65 | $(NuGetCommand) install "$(PackagesConfig)" -source "$(PackageSources)" $(NonInteractiveSwitch) $(RequireConsentSwitch) -solutionDir $(PaddedSolutionDir)
66 | $(NuGetCommand) pack "$(ProjectPath)" -Properties "Configuration=$(Configuration);Platform=$(Platform)" $(NonInteractiveSwitch) -OutputDirectory "$(PackageOutputDir)" -symbols
67 |
68 |
69 |
70 | RestorePackages;
71 | $(BuildDependsOn);
72 |
73 |
74 |
75 |
76 | $(BuildDependsOn);
77 | BuildPackage;
78 |
79 |
80 |
81 |
82 |
83 |
84 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
99 |
100 |
103 |
104 |
105 |
106 |
108 |
109 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |
126 |
141 |
142 |
143 |
144 |
145 |
--------------------------------------------------------------------------------
/AutoBuildEntity/Form/MainForm.xaml.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.ComponentModel;
4 | using System.Linq;
5 | using System.Windows;
6 | using System.Windows.Controls;
7 | using System.Windows.Media;
8 | using 陈珙.AutoBuildEntity.Common.Extension;
9 | using 陈珙.AutoBuildEntity.Common.Helper;
10 | using 陈珙.AutoBuildEntity.Model;
11 | using MessageBox = System.Windows.MessageBox;
12 |
13 | namespace 陈珙.AutoBuildEntity.Form
14 | {
15 | public partial class MainForm : Window
16 | {
17 | #region 窗体初始化
18 | private readonly AutoBuildEntityContent _autoBuildEntityContent;
19 |
20 | private List _hadAddCheckSelectList = new List();
21 |
22 | private List _noAddCheckSelectList = new List();
23 |
24 | private List _noExistCheckSelectList = new List();
25 |
26 | private IEnumerable _noAddList;
27 |
28 | private IEnumerable _hadAddList;
29 |
30 | private IEnumerable _noExistList;
31 |
32 | private readonly string _sqlType;
33 |
34 | public MainForm(AutoBuildEntityContent autoBuildEntityContent, string sqlType)
35 | {
36 | InitializeComponent();
37 | _autoBuildEntityContent = autoBuildEntityContent;
38 | _sqlType = sqlType;
39 | }
40 | #endregion
41 |
42 | #region 加载列表
43 | private void Window_Loaded(object sender, RoutedEventArgs e)
44 | {
45 | //加载列表
46 | _noAddList =
47 | _autoBuildEntityContent.TablesName.Where(
48 | a => !_autoBuildEntityContent.SelectedProject.CsFilesName.Contains(a.ToCaseCamelName()))
49 | .Select(a => new ListViewItem(a)).ToList();
50 |
51 | _hadAddList =
52 | _autoBuildEntityContent.TablesName.Where(
53 | a => _autoBuildEntityContent.SelectedProject.CsFilesName.Contains(a.ToCaseCamelName()))
54 | .Select(a => new ListViewItem(a)).ToList();
55 |
56 | var classList = _autoBuildEntityContent.TablesName.Select(a => a.ToCaseCamelName()).ToList();
57 | _noExistList =
58 | _autoBuildEntityContent.SelectedProject.CsFilesName.Where(
59 | a => !classList.Contains(a))
60 | .Select(a => new ListViewItem(a)).ToList();
61 |
62 | NoAddListView.ItemsSource = _noAddList;
63 | HadAddListView.ItemsSource = _hadAddList;
64 | NoExistListView.ItemsSource = _noExistList;
65 | }
66 | #endregion
67 |
68 | #region 确认提交事件
69 | ///
70 | /// 确认提交事件
71 | ///
72 | ///
73 | ///
74 | private void SubmitEvent(object sender, RoutedEventArgs e)
75 | {
76 | var theSelectedProject = _autoBuildEntityContent.SelectedProject;
77 | try
78 | {
79 | //获取物理表名
80 | var addAndUpdateList = _hadAddCheckSelectList.Union(_noAddCheckSelectList).ToList();
81 | var removeFiles = _noExistCheckSelectList.Select(a => a.ToCaseCamelName() + ".cs").ToList();
82 |
83 | //查询出表结构
84 | var dbTable = new DbTable(_autoBuildEntityContent.EntityXml.ConnString);
85 | var dbtables = dbTable.GetTables(addAndUpdateList, _sqlType);
86 |
87 | //根据模版输出
88 | var templateModel =
89 | dbtables.Select(
90 | a =>
91 | new TemplateModel(a.TableName, a.Columns,
92 | theSelectedProject.ProjectName)).ToList();
93 |
94 | var templateDic = templateModel.ToDictionary(a => a.ClassName,
95 | item =>
96 | NVelocityHelper.ProcessTemplate(_autoBuildEntityContent.EntityXml.EntityTemplate,
97 | new Dictionary { { "entity", item } }));
98 |
99 | //保存文件
100 | foreach (var templateData in templateDic)
101 | {
102 | var path = FilesHelper.WriteAndSave(theSelectedProject.ProjectDirectoryName,
103 | templateData.Key, templateData.Value);
104 |
105 | if (_noAddCheckSelectList.Select(a=>a.ToCaseCamelName()).Contains(templateData.Key))
106 | theSelectedProject.ProjectDte.ProjectItems.AddFromFile(path);
107 | }
108 |
109 | //添加项目项和排除项目项
110 | theSelectedProject.ProjectDte.RemoveFilesFromProject(removeFiles);
111 |
112 | Close();
113 | }
114 | catch (ArgumentException)
115 | {
116 | MessageBox.Show("您的选项在数据库里存在多个项目命名规范的表(视图)名");
117 | }
118 | catch (Exception ex)
119 | {
120 | MessageBox.Show(ex.Message);
121 | }
122 | }
123 | #endregion
124 |
125 | #region 全选
126 | private void HadAddSelectAll_ClickEvent(object sender, RoutedEventArgs e)
127 | {
128 | var cb = sender as CheckBox;
129 |
130 | var hlv = (List)HadAddListView.ItemsSource;
131 | hlv.ForEach(item =>
132 | {
133 | item.IsChecked = cb?.IsChecked ?? false;
134 | });
135 |
136 | _hadAddCheckSelectList = hlv.Where(a => !string.IsNullOrEmpty(a.Name) && a.IsChecked).Select(a => a.Name?.ToString()).ToList();
137 | }
138 |
139 | private void NoAddSelectAll_ClickEvent(object sender, RoutedEventArgs e)
140 | {
141 | var cb = sender as CheckBox;
142 |
143 | var hlv = (List)NoAddListView.ItemsSource;
144 | hlv.ForEach(item =>
145 | {
146 | item.IsChecked = cb?.IsChecked ?? false;
147 | });
148 |
149 | _noAddCheckSelectList = hlv.Where(a => !string.IsNullOrEmpty(a.Name) && a.IsChecked).Select(a => a.Name?.ToString()).ToList();
150 | }
151 |
152 | private void NoExistSelectAll_ClickEvent(object sender, RoutedEventArgs e)
153 | {
154 | var cb = sender as CheckBox;
155 |
156 | var hlv = (List)NoExistListView.ItemsSource;
157 | hlv.ForEach(item =>
158 | {
159 | item.IsChecked = cb?.IsChecked ?? false;
160 | });
161 |
162 | _noExistCheckSelectList = hlv.Where(a => !string.IsNullOrEmpty(a.Name) && a.IsChecked).Select(a => a.Name?.ToString()).ToList();
163 | }
164 | #endregion
165 |
166 | #region CheckBox选中事件
167 | private void TemplateHadAddCheckBox_ClickEvent(object sender, RoutedEventArgs e)
168 | {
169 | var cb = sender as CheckBox;
170 | var tbName = cb.Tag.ToString();
171 | if (cb.IsChecked == true)
172 | {
173 | _hadAddCheckSelectList.Add(tbName);
174 | }
175 | else
176 | {
177 | _hadAddCheckSelectList.Remove(tbName);
178 | }
179 | }
180 |
181 | private void TemplateNoAddCheckBox_ClickEvent(object sender, RoutedEventArgs e)
182 | {
183 | var cb = sender as CheckBox;
184 | var tbName = cb.Tag.ToString();
185 | if (cb.IsChecked == true)
186 | {
187 | _noAddCheckSelectList.Add(tbName);
188 | }
189 | else
190 | {
191 | _noAddCheckSelectList.Remove(tbName);
192 | }
193 | }
194 |
195 | private void TemplateNoExistCheckBox_ClickEvent(object sender, RoutedEventArgs e)
196 | {
197 | var cb = sender as CheckBox;
198 | var tbName = cb.Tag.ToString();
199 | if (cb.IsChecked == true)
200 | {
201 | _noExistCheckSelectList.Add(tbName);
202 | }
203 | else
204 | {
205 | _noExistCheckSelectList.Remove(tbName);
206 | }
207 | }
208 | #endregion
209 |
210 | private void addedSearchBox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
211 | {
212 | FilterList(addedSearchBox, HadAddListView, _hadAddList);
213 | }
214 |
215 | private void unAddSearchBox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
216 | {
217 | FilterList(unAddSearchBox, NoAddListView, _noAddList);
218 | }
219 |
220 | private void unExistSearchBox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
221 | {
222 | FilterList(unExistSearchBox, NoExistListView, _noExistList);
223 | }
224 |
225 | private void FilterList(TextBox tb, ItemsControl clb, IEnumerable data)
226 | {
227 | var selectInput = tb.Text.ToLower();
228 | var resultList = data.Where(a => a.Name.ToLower().StartsWith(selectInput));
229 | clb.ItemsSource = resultList;
230 | }
231 | }
232 |
233 | public class ListViewItem : INotifyPropertyChanged
234 | {
235 | private bool _isChecked;
236 | private string _name;
237 |
238 | public bool IsChecked
239 | {
240 | get => _isChecked;
241 | set
242 | {
243 | if (_isChecked == value) return;
244 | _isChecked = value;
245 | RaisePropertyChanged("IsChecked");
246 | }
247 | }
248 |
249 | public string Name
250 | {
251 | get => _name;
252 | set
253 | {
254 | if (_name == value) return;
255 | _name = value;
256 | RaisePropertyChanged("Name");
257 | }
258 | }
259 |
260 | public ListViewItem(string name)
261 | {
262 | Name = name;
263 | IsChecked = false;
264 | }
265 |
266 | public event PropertyChangedEventHandler PropertyChanged;
267 |
268 | private void RaisePropertyChanged(string propName)
269 | {
270 | var eh = PropertyChanged;
271 | eh?.Invoke(this, new PropertyChangedEventArgs(propName));
272 | }
273 | }
274 | }
275 |
--------------------------------------------------------------------------------
/AutoBuildEntity/AutoBuildEntity.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 15.0
5 | 12.0
6 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)
7 | SAK
8 | SAK
9 | SAK
10 | SAK
11 | ..\
12 | true
13 |
14 |
15 |
16 |
17 | 12.0
18 |
19 | publish\
20 | true
21 | Disk
22 | false
23 | Foreground
24 | 7
25 | Days
26 | false
27 | false
28 | true
29 | 0
30 | 1.0.0.%2a
31 | false
32 | false
33 | true
34 |
35 |
36 |
37 |
38 |
39 | Debug
40 | AnyCPU
41 | 2.0
42 | {D66A2359-0BD8-4BA5-AF0C-A31BD7CDC1BC}
43 | {82b43b9b-a64c-4715-b499-d71e9ca2bd60};{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
44 | Library
45 | Properties
46 | 陈珙.AutoBuildEntity
47 | AutoBuildEntity
48 | True
49 | Key.snk
50 | v4.6.1
51 |
52 |
53 | true
54 | full
55 | false
56 | bin\Debug\
57 | DEBUG;TRACE
58 | prompt
59 | 4
60 |
61 |
62 | pdbonly
63 | true
64 | bin\Release\
65 | TRACE
66 | prompt
67 | 4
68 | true
69 |
70 |
71 |
72 | ..\packages\BouncyCastle.1.8.3.1\lib\BouncyCastle.Crypto.dll
73 |
74 |
75 | ..\packages\EnvDTE.8.0.2\lib\net10\EnvDTE.dll
76 | True
77 |
78 |
79 | ..\packages\EnvDTE80.8.0.3\lib\net10\EnvDTE80.dll
80 | True
81 |
82 |
83 | ..\packages\EnvDTE90.9.0.3\lib\net10\EnvDTE90.dll
84 | True
85 |
86 |
87 | ..\packages\Google.Protobuf.3.6.1\lib\net45\Google.Protobuf.dll
88 |
89 |
90 |
91 |
92 | ..\lib\Microsoft.VisualStudio.Shell.12.0.dll
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 | true
101 |
102 |
103 | true
104 |
105 |
106 |
107 |
108 |
109 |
110 | ..\packages\MySql.Data.8.0.17\lib\net452\MySql.Data.dll
111 |
112 |
113 | ..\packages\NVelocity.1.0.3\lib\NVelocity.dll
114 | True
115 |
116 |
117 |
118 |
119 | ..\packages\SSH.NET.2016.1.0\lib\net40\Renci.SshNet.dll
120 |
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 | {00020430-0000-0000-C000-000000000046}
141 | 2
142 | 0
143 | 0
144 | primary
145 | False
146 | False
147 |
148 |
149 |
150 |
151 |
152 | MainForm.xaml
153 |
154 |
155 |
156 |
157 |
158 | Code
159 |
160 |
161 |
162 |
163 |
164 |
165 |
166 |
167 |
168 |
169 | True
170 | True
171 | Resources.resx
172 |
173 |
174 |
175 |
176 |
177 |
178 |
179 |
180 | ResXFileCodeGenerator
181 | Resources.Designer.cs
182 | Designer
183 |
184 |
185 | true
186 | VSPackage
187 | Designer
188 |
189 |
190 |
191 |
192 |
193 |
194 | Designer
195 |
196 |
197 |
198 |
199 |
200 |
201 |
202 | Menus.ctmenu
203 | Designer
204 |
205 |
206 |
207 |
208 |
209 |
210 |
211 |
212 | Designer
213 | MSBuild:Compile
214 |
215 |
216 |
217 |
218 |
219 | Always
220 | true
221 |
222 |
223 |
224 |
225 | False
226 | .NET Framework 3.5 SP1
227 | false
228 |
229 |
230 |
231 | true
232 |
233 |
234 |
235 |
236 |
237 |
238 | This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.
239 |
240 |
241 |
242 |
243 |
244 |
251 |
--------------------------------------------------------------------------------