(四)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<TT1>");
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;
}

posted @   yingxianqi  阅读(131)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示