(四)EFCore的service层的动态生成,以写入文件的方式生成,类似于代码生成器呢种
1:动态生成Service
#region 动态生成service
public void CreateService(string tableName)
{
string s = System.Environment.CurrentDirectory;
string solutionUrl = new DirectoryInfo(s).Parent.ToString();
string file = ToFirstLower(tableName) + "Service.cs";
#region 生成partial
string createEntityUrl = Path.Combine(solutionUrl, "service\\ef\\partial\\" + file);
if (!System.IO.File.Exists(createEntityUrl))//创建partial的业务层的service
{
StringBuilder entityContent = new StringBuilder();
entityContent.AppendLine("using Entity;");
entityContent.AppendLine("using System;");
entityContent.AppendLine("using System.Collections.Generic;");
entityContent.AppendLine("using System.Text;");
entityContent.AppendLine("namespace service.ef");
entityContent.AppendLine(" {");
entityContent.AppendLine(" public partial class " + ToFirstLower(tableName) + "Service");
entityContent.AppendLine(" {");
entityContent.AppendLine(" };");
entityContent.AppendLine(" };");
//创建文件
FileStream fs = new FileStream(createEntityUrl, FileMode.Create, FileAccess.ReadWrite); //可以指定盘符,也可以指定任意文件名,还可以为word等文件 OpenOrCreate
StreamWriter sw = new StreamWriter(fs); // 创建写入流
sw.WriteLine(entityContent);
sw.Close(); //关闭文件
}
#endregion
string MaincreateMainEntityUrl = Path.Combine(solutionUrl, "service\\ef\\" + file);
StringBuilder MainentityContent = new StringBuilder();
MainentityContent.AppendLine("using DbEntity.dbprogram;");
MainentityContent.AppendLine("using DbMs;");
MainentityContent.AppendLine("using Entity;");
MainentityContent.AppendLine("using System;");
MainentityContent.AppendLine("using System.Collections.Generic;");
MainentityContent.AppendLine("using System.Text;");
MainentityContent.AppendLine("namespace service.ef");
MainentityContent.AppendLine(" {");
MainentityContent.AppendLine(" public partial class " + ToFirstLower(tableName) + "Service : EfDbGet
MainentityContent.AppendLine(" {");
MainentityContent.AppendLine(" public " + ToFirstLower(tableName) + "Service(PmsContext context) : base(context)");
MainentityContent.AppendLine(" {");
MainentityContent.AppendLine(" }");
MainentityContent.AppendLine(" };");
MainentityContent.AppendLine(" };");
//创建文件
FileStream Mainfs = new FileStream(MaincreateMainEntityUrl, FileMode.Create, FileAccess.ReadWrite); //可以指定盘符,也可以指定任意文件名,还可以为word等文件 OpenOrCreate
StreamWriter Mainsw = new StreamWriter(Mainfs); // 创建写入流
Mainsw.WriteLine(MainentityContent);//创建partial的固定层的service
Mainsw.Close(); //关闭文件
#endregion
2:将表的首写字母转换成大写字母
public string ToFirstLower(string fildName)
{
string first = fildName.Substring(0, 1).ToUpper();
string rest = fildName.Substring(1, fildName.Length - 1);
string newStr = new StringBuilder(first).Append(rest).ToString();
return newStr;
}