From 9b789010bb6dad9c99ee1c21fb0ff85f93a9d2e9 Mon Sep 17 00:00:00 2001 From: sunkaixuan <610262374@qq.com> Date: Thu, 17 Jan 2019 00:58:05 +0800 Subject: [PATCH] Update Demo --- .../SugarCodeGeneration/Codes/BLLParameter.cs | 7 + .../Codes/DbContextParameter.cs | 12 ++ .../SugarCodeGeneration/Codes/FileHelper.cs | 70 +++++++++ .../SugarCodeGeneration/Codes/Methods.cs | 35 ++++- .../SugarCodeGeneration/Models/School.cs | 31 ---- .../SugarCodeGeneration/Models/Student.cs | 66 --------- Src/Asp.Net/SugarCodeGeneration/Program.cs | 139 +++++++++++++++--- .../SugarCodeGeneration.csproj | 18 ++- .../SugarCodeGeneration/Template/BLL.txt | 7 + .../Template/DbContext.txt | 80 ++++++++++ .../SugarCodeGeneration/packages.config | 2 + 11 files changed, 348 insertions(+), 119 deletions(-) create mode 100644 Src/Asp.Net/SugarCodeGeneration/Codes/BLLParameter.cs create mode 100644 Src/Asp.Net/SugarCodeGeneration/Codes/DbContextParameter.cs create mode 100644 Src/Asp.Net/SugarCodeGeneration/Codes/FileHelper.cs delete mode 100644 Src/Asp.Net/SugarCodeGeneration/Models/School.cs delete mode 100644 Src/Asp.Net/SugarCodeGeneration/Models/Student.cs create mode 100644 Src/Asp.Net/SugarCodeGeneration/Template/BLL.txt create mode 100644 Src/Asp.Net/SugarCodeGeneration/Template/DbContext.txt diff --git a/Src/Asp.Net/SugarCodeGeneration/Codes/BLLParameter.cs b/Src/Asp.Net/SugarCodeGeneration/Codes/BLLParameter.cs new file mode 100644 index 000000000..34eb1ff44 --- /dev/null +++ b/Src/Asp.Net/SugarCodeGeneration/Codes/BLLParameter.cs @@ -0,0 +1,7 @@ +namespace SugarCodeGeneration +{ + public class BLLParameter + { + public string Name { get; set; } + } +} \ No newline at end of file diff --git a/Src/Asp.Net/SugarCodeGeneration/Codes/DbContextParameter.cs b/Src/Asp.Net/SugarCodeGeneration/Codes/DbContextParameter.cs new file mode 100644 index 000000000..0bee0bed1 --- /dev/null +++ b/Src/Asp.Net/SugarCodeGeneration/Codes/DbContextParameter.cs @@ -0,0 +1,12 @@ +using System.Collections.Generic; +using SqlSugar; + +namespace SugarCodeGeneration +{ + public class DbContextParameter + { + public string ConnectionString { get; set; } + public DbType DbType { get; set; } + public List Tables { get; set; } + } +} \ No newline at end of file diff --git a/Src/Asp.Net/SugarCodeGeneration/Codes/FileHelper.cs b/Src/Asp.Net/SugarCodeGeneration/Codes/FileHelper.cs new file mode 100644 index 000000000..feb6ed5a0 --- /dev/null +++ b/Src/Asp.Net/SugarCodeGeneration/Codes/FileHelper.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; + +namespace SugarCodeGeneration.Codes +{ + internal class FileHelper + { + public static void CreateFile(string filePath, string text, Encoding encoding) + { + try + { + if (IsExistFile(filePath)) + { + DeleteFile(filePath); + } + if (!IsExistFile(filePath)) + { + string directoryPath = GetDirectoryFromFilePath(filePath); + CreateDirectory(directoryPath); + + //Create File + FileInfo file = new FileInfo(filePath); + using (FileStream stream = file.Create()) + { + using (StreamWriter writer = new StreamWriter(stream, encoding)) + { + writer.Write(text); + writer.Flush(); + } + } + } + } + catch(Exception ex) + { + throw ex; + } + } + public static bool IsExistDirectory(string directoryPath) + { + return Directory.Exists(directoryPath); + } + public static void CreateDirectory(string directoryPath) + { + if (!IsExistDirectory(directoryPath)) + { + Directory.CreateDirectory(directoryPath); + } + } + public static void DeleteFile(string filePath) + { + if (IsExistFile(filePath)) + { + File.Delete(filePath); + } + } + public static string GetDirectoryFromFilePath(string filePath) + { + FileInfo file = new FileInfo(filePath); + DirectoryInfo directory = file.Directory; + return directory.FullName; + } + public static bool IsExistFile(string filePath) + { + return File.Exists(filePath); + } + } +} diff --git a/Src/Asp.Net/SugarCodeGeneration/Codes/Methods.cs b/Src/Asp.Net/SugarCodeGeneration/Codes/Methods.cs index 859180a2e..b6de26de5 100644 --- a/Src/Asp.Net/SugarCodeGeneration/Codes/Methods.cs +++ b/Src/Asp.Net/SugarCodeGeneration/Codes/Methods.cs @@ -4,9 +4,14 @@ using System.IO; using System.Linq; using System.Text; using System.Xml.Linq; +using RazorEngine; +using RazorEngine.Templating; namespace SugarCodeGeneration.Codes { + /// + /// 生成所需要的代码 + /// public class Methods { public static string GetCurrentProjectPath @@ -31,11 +36,14 @@ namespace SugarCodeGeneration.Codes public static void AddCsproj(string classPath, string projectName) { var classDirectory = Methods.GetSlnPath + "\\" +projectName+"\\"+ classPath.TrimStart('\\'); + if (FileHelper.IsExistDirectory(classDirectory) == false) { + FileHelper.CreateDirectory(classDirectory); + } var files = Directory.GetFiles(classDirectory).ToList().Select(it=>classPath+"\\"+Path.GetFileName(it)); var xmlPath = GetSlnPath + @"\" + projectName + @"\SugarCodeGeneration.csproj"; - var xml = File.ReadAllText(xmlPath,Encoding.UTF8); - var firstLine = System.IO.File.ReadLines(xmlPath, Encoding.UTF8).First(); + var xml = File.ReadAllText(xmlPath, System.Text.Encoding.UTF8); + var firstLine = System.IO.File.ReadLines(xmlPath, System.Text.Encoding.UTF8).First(); var newXml = xml.Replace(firstLine, "").TrimStart('\r').TrimStart('\n'); XDocument xe = XDocument.Load(xmlPath); var itemGroup=xe.Root.Elements().Where(it=>it.Name.LocalName== "ItemGroup"&&it.Elements().Any(y=>y.Name.LocalName== "Compile")).First(); @@ -52,5 +60,28 @@ namespace SugarCodeGeneration.Codes xe = XDocument.Parse(newXml); xe.Save(xmlPath); } + + public static void CreateBLL(string templatePath, string savePath,List tables) + { + + string template = System.IO.File.ReadAllText(templatePath); //从文件中读出模板内容 + string templateKey = "bll"; //取个名字 + foreach (var item in tables) + { + BLLParameter model = new BLLParameter() + { + Name=item + }; + var result = Engine.Razor.RunCompile(template, templateKey, model.GetType(), model); + FileHelper.CreateFile(savePath+"\\"+item+ "Manager.cs", result, System.Text.Encoding.UTF8); + } + } + + public static void CreateDbContext(string templatePath, string savePath, object model) { + string template = System.IO.File.ReadAllText(templatePath); //从文件中读出模板内容 + string templateKey ="dbcontext"; //取个名字 + var result =Engine.Razor.RunCompile(template, templateKey, model.GetType(), model); + FileHelper.CreateFile(savePath, result, System.Text.Encoding.UTF8); + } } } diff --git a/Src/Asp.Net/SugarCodeGeneration/Models/School.cs b/Src/Asp.Net/SugarCodeGeneration/Models/School.cs deleted file mode 100644 index 0cc892644..000000000 --- a/Src/Asp.Net/SugarCodeGeneration/Models/School.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; -using System.Linq; -using System.Text; - -namespace MyTest -{ - /// - /// - /// - public partial class School - { - public School(){ - - - } - /// - /// Desc: - /// Default: - /// Nullable:False - /// - public int Id {get;set;} - - /// - /// Desc: - /// Default: - /// Nullable:True - /// - public string Name {get;set;} - - } -} diff --git a/Src/Asp.Net/SugarCodeGeneration/Models/Student.cs b/Src/Asp.Net/SugarCodeGeneration/Models/Student.cs deleted file mode 100644 index e86fd7009..000000000 --- a/Src/Asp.Net/SugarCodeGeneration/Models/Student.cs +++ /dev/null @@ -1,66 +0,0 @@ -using System; -using System.Linq; -using System.Text; - -namespace MyTest -{ - /// - /// - /// - public partial class Student - { - public Student(){ - - - } - /// - /// Desc: - /// Default: - /// Nullable:False - /// - public int Id {get;set;} - - /// - /// Desc: - /// Default:1 - /// Nullable:True - /// - public int? SchoolId {get;set;} - - /// - /// Desc:Student Name - /// Default: - /// Nullable:True - /// - public string Name {get;set;} - - /// - /// Desc: - /// Default:DateTime.Now - /// Nullable:True - /// - public DateTime? CreateTime {get;set;} - - /// - /// Desc: - /// Default: - /// Nullable:True - /// - public byte[] Timestamp {get;set;} - - /// - /// Desc: - /// Default: - /// Nullable:True - /// - public DateTimeOffset? Datetimeoffset {get;set;} - - /// - /// Desc: - /// Default: - /// Nullable:True - /// - public double? Float {get;set;} - - } -} diff --git a/Src/Asp.Net/SugarCodeGeneration/Program.cs b/Src/Asp.Net/SugarCodeGeneration/Program.cs index 7dbc7e60e..fdb1d4760 100644 --- a/Src/Asp.Net/SugarCodeGeneration/Program.cs +++ b/Src/Asp.Net/SugarCodeGeneration/Program.cs @@ -5,34 +5,139 @@ using System.Diagnostics; using System.IO; using System.Linq; using System.Text; +using System.Threading.Tasks; using static System.Net.Mime.MediaTypeNames; namespace SugarCodeGeneration { class Program { - private const SqlSugar.DbType sqlServer = SqlSugar.DbType.SqlServer; - private const string projectName = "SugarCodeGeneration"; - private const string classPath= "Models"; - private const string classNamespace = "MyTest"; - private const string connectionString = "server=.;uid=sa;pwd=@jhl85661501;database=SqlSugar4XTest"; + const SqlSugar.DbType dbType = SqlSugar.DbType.SqlServer; + const string connectionString = "server=.;uid=sa;pwd=@jhl85661501;database=SqlSugar4XTest"; + static List CsprojList = new List(); + static SqlSugar.SqlSugarClient GetDB() + { + + return new SqlSugar.SqlSugarClient(new SqlSugar.ConnectionConfig() + { + DbType = dbType, + ConnectionString = connectionString, + IsAutoCloseConnection = true, + InitKeyType=SqlSugar.InitKeyType.Attribute + }); + } static void Main(string[] args) { - //Generation model - SqlSugar.SqlSugarClient db = new SqlSugar.SqlSugarClient(new SqlSugar.ConnectionConfig() { - DbType = sqlServer, + //生成实体 + GenerationClass(); + Console.WriteLine("实体创建成功"); + Console.WriteLine(""); + + //生成DbContext + GenerationDContext(); + Console.WriteLine("DbContext创建成功"); + Console.WriteLine(""); + + //生成BLL类 + GenerationBLL(); + Console.WriteLine("Bll创建成功"); + Console.WriteLine(""); + + //修改解决方案 + UpdateCsproj(); + Console.WriteLine("项目解决方案修改成功"); + Console.ReadKey(); + + //test bll + + } + + + /// + /// 生成BLL + /// + private static void GenerationBLL() + { + var db = GetDB(); + + //配置参数 + var templatePath = Methods.GetCurrentProjectPath + "\\Template\\Bll.txt";//bll模版地址 + var bllProjectName = "SugarCodeGeneration";//具体项目 + var bllPath = "BLL";//文件目录 + var savePath = Methods.GetSlnPath + "\\" + bllProjectName + "\\" + bllPath;//保存目录 + var tables = db.DbMaintenance.GetTableInfoList().Where(it => it.Name == "Student" || it.Name == "School").Select(it => it.Name).ToList(); + + //下面代码不动 + Methods.CreateBLL(templatePath, savePath, tables); + AddTask(bllProjectName, bllPath); + } + + + + /// + /// 生成DbContext + /// + private static void GenerationDContext() + { + var db = GetDB(); + + + //配置参数 + var templatePath = Methods.GetCurrentProjectPath + "\\Template\\DbContext.txt";//dbcontexts模版文件 + var contextProjectName = "SugarCodeGeneration";//DbContext所在项目 + var contextPath = "DbContext";//dbcontext存储目录 + var savePath = Methods.GetSlnPath + "\\" + contextProjectName + "\\" + contextPath+"\\DbContext.cs";//具体文件名 + var tables = db.DbMaintenance.GetTableInfoList().Where(it => it.Name == "Student" || it.Name == "School").Select(it => it.Name).ToList(); + + //下面代码不动 + var model = new DbContextParameter{ ConnectionString = connectionString, - IsAutoCloseConnection = true + DbType = dbType, + Tables = tables + }; + + + Methods.CreateDbContext(templatePath,savePath,model); + AddTask(contextPath, contextProjectName); + } + + /// + /// 生成实体类 + /// + private static void GenerationClass() + { + + string classProjectName = "SugarCodeGeneration";//实体类项目名称 + string classPath = "Models";//生成的目录 + string classNamespace = "MyTest";//实体命名空间 + var db = GetDB(); + var classDirectory = Methods.GetSlnPath + "\\" + classProjectName + "\\" + classPath.TrimStart('\\'); + + //如果生成全部可以把Where去掉 + db.DbFirst.Where("Student", "School").IsCreateAttribute().CreateClassFile(classDirectory, classNamespace); + + AddTask(classPath, classProjectName); + } + + /// + /// 修改解决方案 + /// + private static void UpdateCsproj() + { + foreach (var item in CsprojList) + { + item.Start(); + } + } + + private static void AddTask(string bllProjectName, string bllPath) + { + var task = new Task(() => + { + Methods.AddCsproj(bllPath, bllProjectName); }); - var classDirectory = Methods.GetSlnPath +"\\"+projectName+"\\"+ classPath.TrimStart('\\'); - - //if all then remove .Where - db.DbFirst.Where("Student","School").CreateClassFile(classDirectory, classNamespace); - - Methods.AddCsproj(classPath, projectName); - - //Generation DbContext + CsprojList.Add(task); } } } diff --git a/Src/Asp.Net/SugarCodeGeneration/SugarCodeGeneration.csproj b/Src/Asp.Net/SugarCodeGeneration/SugarCodeGeneration.csproj index 9b9c0576d..a4fe03ace 100644 --- a/Src/Asp.Net/SugarCodeGeneration/SugarCodeGeneration.csproj +++ b/Src/Asp.Net/SugarCodeGeneration/SugarCodeGeneration.csproj @@ -11,7 +11,8 @@ v4.0 512 true - + + AnyCPU @@ -48,6 +49,10 @@ ..\packages\Oracle.ManagedDataAccess.18.3.0\lib\net40\Oracle.ManagedDataAccess.dll + + ..\packages\RazorEngine.3.10.0\lib\net40\RazorEngine.dll + True + ..\packages\sqlSugar.4.9.7.5\lib\SqlSugar.dll @@ -65,6 +70,10 @@ ..\packages\System.Data.SQLite.Linq.1.0.109.0\lib\net40\System.Data.SQLite.Linq.dll True + + ..\packages\Microsoft.AspNet.Razor.2.0.30506.0\lib\net40\System.Web.Razor.dll + True + @@ -72,9 +81,10 @@ - + + + - @@ -84,6 +94,8 @@ + + Always diff --git a/Src/Asp.Net/SugarCodeGeneration/Template/BLL.txt b/Src/Asp.Net/SugarCodeGeneration/Template/BLL.txt new file mode 100644 index 000000000..11328e7c1 --- /dev/null +++ b/Src/Asp.Net/SugarCodeGeneration/Template/BLL.txt @@ -0,0 +1,7 @@ +using MyTest; +public class @(Model.Name)Manager : DbContext<@Model.Name> +{ + + //我们如果有特殊需要可以重写DbContext中默认 增、删、查、改、方法 + +} \ No newline at end of file diff --git a/Src/Asp.Net/SugarCodeGeneration/Template/DbContext.txt b/Src/Asp.Net/SugarCodeGeneration/Template/DbContext.txt new file mode 100644 index 000000000..c2fe1c574 --- /dev/null +++ b/Src/Asp.Net/SugarCodeGeneration/Template/DbContext.txt @@ -0,0 +1,80 @@ +using MyTest; +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +public class DbContext where T : class, new() +{ + public DbContext() + { + Db = new SqlSugarClient(new ConnectionConfig() + { + ConnectionString = "@Model.ConnectionString", + DbType = DbType.@Model.DbType, + InitKeyType = InitKeyType.Attribute,//从特性读取主键和自增列信息 + IsAutoCloseConnection = true,//开启自动释放模式和EF原理一样我就不多解释了 + + }); + //调式代码 用来打印SQL + Db.Aop.OnLogExecuting = (sql, pars) => + { + Console.WriteLine(sql + "\r\n" + + Db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value))); + Console.WriteLine(); + }; + + } + //注意:不能写成静态的 + public SqlSugarClient Db;//用来处理事务多表查询和复杂的操作 + public SimpleClient CurrentDb { get { return new SimpleClient(Db); } } + + @foreach(var item in @Model.Tables) + { + @: public SimpleClient<@item> @(item)Db { get { return new SimpleClient<@item>(Db); } }//用来处理Student表的常用操作 + } + + + /// + /// 获取所有 + /// + /// + public virtual List GetList() + { + return CurrentDb.GetList(); + } + + /// + /// 根据主键删除 + /// + /// + /// + public virtual bool Delete(dynamic id) + { + return CurrentDb.Delete(id); + } + + + /// + /// 更新 + /// + /// + /// + public virtual bool Update(T obj) + { + return CurrentDb.Update(obj); + } + + /// + /// 插入 + /// + /// + /// + public virtual bool Insert(T obj) + { + return CurrentDb.Insert(obj); + } + + //自已扩展更多方法 +} + + diff --git a/Src/Asp.Net/SugarCodeGeneration/packages.config b/Src/Asp.Net/SugarCodeGeneration/packages.config index 642733869..7aebe267e 100644 --- a/Src/Asp.Net/SugarCodeGeneration/packages.config +++ b/Src/Asp.Net/SugarCodeGeneration/packages.config @@ -1,9 +1,11 @@  + +