首页 > 数据库 >019 数据库学习笔记--代码生成工具(满满的成产力)

019 数据库学习笔记--代码生成工具(满满的成产力)

时间:2023-10-11 17:03:20浏览次数:39  
标签:代码生成 -- TableName when print 019 List public

-------------------------------生成实体类-------------------------------
declare @TableName sysname = 'ViewQualityInfo'   
declare @TableNameL sysname = 'viewQualityInfo'
declare @Result varchar(max) = '
/// <summary>
/// ' + @TableName +

'
/// </summary>
public class ' + @TableName + '
{'
	select @Result = @Result + '
	public ' + ColumnType + NullableSign + ' ' + ColumnName + ' { get; set; }'
from
(
SELECT
replace(col.name, ' ', '_') ColumnName,
column_id ColumnId,
prop.value ColName,
case typ.name
when 'bigint' then 'long'
when 'binary' then 'byte[]'
when 'bit' then 'bool'
when 'char' then 'string'
when 'date' then 'DateTime'
when 'datetime' then 'DateTime'
when 'datetime2' then 'DateTime'
when 'datetimeoffset' then 'DateTimeOffset'
when 'decimal' then 'decimal'
when 'float' then 'float'
when 'image' then 'byte[]'
when 'int' then 'int'
when 'money' then 'decimal'
when 'nchar' then 'char'
when 'ntext' then 'string'
when 'numeric' then 'decimal'
when 'nvarchar' then 'string'
when 'real' then 'double'
when 'smalldatetime' then 'DateTime'
when 'smallint' then 'short'
when 'smallmoney' then 'decimal'
when 'text' then 'string'
when 'time' then 'TimeSpan'
when 'timestamp' then 'DateTime'
when 'tinyint' then 'byte'
when 'uniqueidentifier' then 'Guid'
when 'varbinary' then 'byte[]'
when 'varchar' then 'string'
else 'UNKNOWN_' + typ.name
end ColumnType,
case
when col.is_nullable = 1 and typ.name in ('bigint', 'bit', 'date', 'datetime', 'datetime2', 'datetimeoffset', 'decimal', 'float', 'int', 'money', 'numeric', 'real', 'smalldatetime', 'smallint', 'smallmoney', 'time', 'tinyint', 'uniqueidentifier')
then '?'
else ''
end NullableSign
from sys.columns col
join sys.types typ on
col.system_type_id = typ.system_type_id AND col.user_type_id = typ.user_type_id
LEFT JOIN sys.extended_properties prop ON col.object_id = prop.major_id AND col.column_id = prop.minor_id
where object_id = object_id(@TableName)
) t
--order by ColumnId

set @Result = @Result + '
}'

print @Result

print''
print 'public class ' + @TableName + 'Params'
print'{'
print '	public string BeginDate { get; set; }'
print '	public string EndDate { get; set; }'
print '}'

-------------------------------生成实体类end-------------------------------
print ''
--IDAL
--public partial interface IDictQualityItemsDal : IBaseDal<DictQualityItems>
print 'public partial interface I'+@TableName +'Dal : IBaseDal<'+ @TableName +'>'
print'{'
print'	bool Inserts(List<'+@TableName+'> objs);'
print'	bool DeleteByIds(List<string> ids);'
print'	bool UpdateIsEnable(List<string> ids, string isEnable);'
print'	bool Updates(List<'+@TableName+'> objs);'
print '}'
print''
    --bool Inserts(List<DictQualityItems> objs);
    --bool DeleteByIds(List<string> ids);
    --bool UpdateIsEnable(List<string> ids, string isEnable);
	

--DAL
--public partial class DictQualityItemsDal : BaseDal<DictQualityItems>, IDictQualityItemsDal
print 'public partial class '+@TableName +'Dal : BaseDal<'+ @TableName +'>,I'+@TableName+'Dal'
print'{'
--add
print'	public bool Inserts(List<'	+ @TableName +'> objs)'
print'	{'	
print'	 bool value = false;'	
print'	 try'	
print'	 {'	
--print'		new BaseDal<'+	@TableName+'>().Db.UseTransaction(() =>'
print'		this.Db.UseTransaction(() =>'
print'		{'	
print'			foreach ('+@TableName+' temp in objs)'
print'			{'	
print'				temp.Id = Guid.NewGuid().ToString("N");'	
print'				temp.CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");'	
print'				this.Add(temp);'	
print'			}'	
print'		});'	
print'	'	
print'		value = true;'	
print'	  }'	
print'	  catch (Exception) { throw; }'
print'	'	
print'	  return value;'	
print'	}'	
print'	'	

--del
print'public bool DeleteByIds(List<string> ids)'	
print'{'
print'	bool value = false;'	
print'	try'
print'	{'	
--print'		new BaseDal<'+	@TableName+'>().Db.UseTransaction(() =>'
print'		this.Db.UseTransaction(() =>'
print'		{'	
print'			foreach (string id in ids)'	
print'			{'
print'				this.Delete<'+	@TableName+'>(o => o.Id.Equals(id));'	
print'			}'
print'		});'	
print''
print'		value = true;'	
print'	}'
print'	catch (Exception) { throw; }'	
print''
print'	return value;'
print'}'
print''
--UpdateIsEnable
print'public bool UpdateIsEnable(List<string> ids, string isEnable)'	
print'{'
print'	bool value = false;'	
print'	try'
print'	{'	
print'		this.Db.UseTransaction(() =>'
print'		{'	
print'		 foreach (string id in ids)'
print'		 {'
print'			int count = this.Update<'+@TableName+'('
print'			o => o.Id.ToString().Equals(id), o => new '+@TableName+'()'
print'			{'
print'				IsEnable = isEnable'
print'		    });'	
print'		}'
print'	  });'	
print'	}'
print'	catch (Exception)'	
print'	{'
print'		value = false;'
print'		throw;'
print'	}'
print''
print'	return value;'
print'}'
print''
--Updates
print'public bool Updates(List<' +@TableName+'> objs)'
print'{'	
print'	bool value = false;'	
print'	try'	
print'	{'	
--print'		new BaseDal<'+	@TableName+'>().Db.UseTransaction(() =>'
print'		this.Db.UseTransaction(() =>'
print'		{'	
print'			foreach ('+@TableName+' temp in objs)'
print'			{'	
print'			this.Update<'+@TableName+'('
print'			o => o.Id.ToString().Equals(id), o => new '+@TableName+'()'
print'			{'
print'				IsEnable = temp.IsEnable,'
print'		    });'	
print'		}'
print'	}'
print'	catch (Exception)'	
print'	{'
print'		value = false;'
print'		throw;'
print'	}'
print''
print'	return value;'
print' }'
--类结束
print'}'
print ''


--IService
 --public partial interface IDictReviewItemsService : IBaseService<DictReviewItems>
 --List<ViewReportInfo> GetViewReportInfo(ViewReportInfoParams mode);
print 'public partial interface I'+@TableName +'Service : IBaseService<'+ @TableName +'>'
print'{'
print'	bool Inserts(List<'+@TableName+'> objs);'
print'	bool DeleteByIds(List<string> ids);'
print'	bool UpdateIsEnable(List<string> ids, string isEnable);'
print'	bool Updates(List<'+@TableName+'> objs);'
print'	List<'+@TableName+'> Get'+@TableName+'('+@TableName+'Params mode);'
print'	List<'+@TableName+'> Get'+@TableName+'('+@TableName+'Params mode,int pageSize, int pageIndex, out int totalCount);'
print '}'
print ''


--Service
--public partial class DictQualityItemsService : BaseService<DictQualityItems>, IDictQualityItemsService
--private IDictQualityItemsDal Dal = new DictQualityItemsDal();
--public override void SetCurrentDal()
--CurrentDal = new DictQualityItemsDal();
print 'public partial class '+@TableName +'Service : BaseService<'+ @TableName +'>,I'+@TableName+'Service'
print '{'
print '	private I'+ @TableName +'Dal Dal = new '+@TableName +'Dal();'
print '	public override void SetCurrentDal()'
print '	{'
print '		CurrentDal = new '+ @TableName +'Dal();'
print '	}'
print''
--add
print'public bool Inserts(List<'+ @TableName +'> objs)'
print'{'
print'	return Dal.Inserts(objs);'
print'}'
print''
--del
print'public bool DeleteByIds(List<string> ids)'
print'{'
print'	return Dal.DeleteByIds(ids);'
print'}'
print''
--UpdateIsEnable
print'public bool UpdateIsEnable(List<string> ids, string isEnable)'
print'{'
print'	return Dal.UpdateIsEnable(ids, isEnable);'
print'}'
print''
--Updates
print'public bool Updates(List<'+ @TableName +'> objs)'
print'{'
print'	return Dal.Updates(objs);'
print'}'
print''
--查询方法
print '	public List<'+@TableName+'> Get'+@TableName+'('+@TableName+'Params mode)'
print '	{'
print'			List<'+@TableName+'> list = new List<' + @TableName +'>();'		
print'			Expression<Func<'+@TableName+', bool>> where = o => o.Id == o.Id;'
print'			string beginDate = mode.BeginDate + " 00:00:00";'	
print'			string endDate = mode.EndDate + " 23:59:59";'	
print'			where = where.And(o => DateTime.Parse(o.AuditTime) >= DateTime.Parse(beginDate)'
print'			&& DateTime.Parse(o.AuditTime) <= DateTime.Parse(endDate));'
print''
print'			if (!string.IsNullOrEmpty(mode.Organization))'
print'			where = where.And(o => o.Organization == mode.Organization);'
print''
print'			list = CurrentDal.GetEntities(where)'
print'			.OrderBy(o => o.Organization)'
print'			.ThenBy(o => o.ClassName)'
print'			.ToList();'
print''
print'			return list;'	  
print '	}'

--分页查询方法
print''
print '	public List<'+@TableName+'> Get'+@TableName+'('+@TableName+'Params mode,int pageSize, int pageIndex, out int totalCount)'
print '	{'
print'			List<'+@TableName+'> result = new List<' + @TableName +'>();'		
print'			totalCount = 0;'	  	
print'			try'
print'			{'
print'				Expression<Func<'+@TableName+', bool>> where = o => o.Id == o.Id;'
print'				if (mode != null) where = GetWhere(mode);'
print'				totalCount = new BaseDal<'+@TableName+'>().Db.Query<'+@TableName+'>().Where(where).Count();'
print''
print'				result = new BaseDal<'+@TableName+'>().Db.Query<'+@TableName+'>().Where(where)'
print'				.OrderByDesc(o => o.OrganizationName)'
print'				.ThenByDesc(o => o.Modality)'
print'				.ThenBy(o => o.Status)'
print'				.Skip(pageSize * (pageIndex - 1))'
print'				.Take(pageSize)'
print'				.ToList();'
print'			}'
print'			catch (Exception ex)'
print'			{'
print'				LogHelper.ErrorFormat("'+@TableName+'Service Get'+@TableName+'-{0}", ex);'
print'			}'
print'			return result;'	  
print '	}'
print''
--where
print'	private Expression<Func<'+@TableName+', bool>> GetWhere('+@TableName+'Params mode)'
print'	{'
print'		string beginDate = mode.BeginDate + " 00:00:00";'	
print'		string endDate = mode.EndDate + " 23:59:59";'	
print'		Expression<Func<'+@TableName+', bool>> where = o => o.Id == o.Id;'
print'		where = where.And(o => DateTime.Parse(o.AuditTime) >= DateTime.Parse(beginDate)'
print'		&& DateTime.Parse(o.AuditTime) <= DateTime.Parse(endDate));'
print''
print'		if (!string.IsNullOrEmpty(mode.Organization))'
print'		where = where.And(o => o.Organization == mode.Organization);'
print''
print'		return list;'	  
print'   }'
print '}'

--Controller
declare @Controller varchar(max) = 
'
/// <summary>
/// ' + @TableName + 

' 控制器
/// </summary>' + char(13)
+'[ApiController]' +char(13)
+'public class ' + @TableName + 'Controller : ControllerBase'+char(13)
+'{'+char(13) 
+ '	#region 定义' + char(13)
+ '	/// <summary>
	///  I' + @TableName + 'Service ' + @TableName + 'Service 
	/// </summary>' + char(13)
+'	private I'+ @TableName + 'Service ' + @TableName + 'Service; '
+'
	/// <summary>
	///  初始化服务信息
	/// </summary>' + char(13)
	+'	/// <param name="'+@TableNameL+'Service">I' + @TableName + 'Service ' + @TableNameL + 'Service</param>' + char(13)
	+'	public '+ @TableName + 'Controller(I' + @TableName+ 'Service ' + @TableNameL + 'service)'+ char(13)
	+'	{'+char(13) 
	+ '		'+@TableName+ 'Service = ' + @TableNameL+ 'Service;'+char(13)
	+'	}'+char(13)
+ char(13)+ '	#endregion' + char(13) + char(13)
+'}'+char(13) 

print @Controller
-- 注册服务代码
print('services.AddScoped<I' + @TableName + 'Service,' + @TableName + 'Service>();')

  

标签:代码生成,--,TableName,when,print,019,List,public
From: https://www.cnblogs.com/YYkun/p/17757625.html

相关文章

  • 视频监控系统/安防视频平台EasyCVR广场视频细节优化
    安防视频监控系统/视频云存储/安防监控EasyCVR视频汇聚平台基于云边端智能协同,支持海量视频的轻量化接入与汇聚、转码与处理、全网智能分发、视频集中存储等。安防视频汇聚平台EasyCVR拓展性强,视频能力丰富,可实现视频监控直播、视频轮播、视频录像、云存储、回放与检索、智能告警......
  • java 后台防止重复提交(注解方式)
    /***自定义注解防止表单重复提交**@authorframework*/@Inherited@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic@interfaceRepeatSubmit{/***间隔时间(ms),小于此时间视为重复提交*/intinterval(......
  • 一键切换jdk
    一键切换jdk原理为脚本修改环境变量jdk8.cmd@echooff::获取管理员权限%1mshtavbscript:CreateObject("Shell.Application").ShellExecute("cmd.exe","/c%~s0::","","runas",1)(window.close)&&exitcd/d"%~dp0"......
  • python 获取word页数
    没想到获取个word页数这么简单的需求,实现起来还挺难。1.根据网上说法:word文档中不保存总页数,只是在渲染时才根据文字和表格等去摆放到一页上,摆放不下时才展现下一页。所以从docx中取不到总页数2.因此,仅用docx库不行,还需要用win32com。而win32com实际是:pipinstallpypiwin32 ......
  • 时间、顺序与一致性
    一、背景分布式架构下,需要协调不同节点之间的先来后到,但不同节点又没有统一承认的时间标准,于是创造了网络时间协议(NTP)试图来解决不同节点之间的时间标准,但是NTP本身表现并不如人意,所以又构造出了逻辑时钟,最后在逻辑时钟的基础上改进为了向量时钟二、时间标准分类1. 网络时......
  • 关于CH32V系列MCU中断优先级配置以及硬件压栈
    从下图可以看出,第二列与第三列分别为优先级与优先级类型,优先级类型又分为两种,其一是固定优先级,其二是可编程的优先级。以RTC为例,优先级为5,优先级类型为可编程,代表着在不配置RTC的优先级时默认为5,如果需要,也可以将其配置为更高的优先级进行响应。下图关于中断优先级配置,针对CH32V......
  • word如何标题编号不乱
    一问题每回标题编号都乱的一批,得手动调整,这次学习视频中,留意一下里面的操作,恍然大悟,还是三人行,有我师哇,关门造车,造个寂寞 二解决先写字,再选择样式,让系统自己生成标题 ......
  • celery定时任务与周期任务
    celery定时任务与周期任务创建celery定时任务的方法与方式创建celery的定时任务有很多,我们这里只提到笔者使用过的首先你需要创建两个文件。第一个文件为celery配置一些东西。importos,djangoos.environ.setdefault("DJANGO_SETTINGS_MODULE","settings")django.setup(......
  • Microsoft SQL Server导出数据为sql文件以及sql文件的执行
    一.MicrosoftSQLServer导出数据为sql文件1.在数据库上右击选择“任务”/“生成脚本” 2.在选择对象对话框中选择你要导出的实例 3.在“高级脚本编写选项”的“常规”的“编写脚本的数据类型”设置为“架构和数据/仅限数据/仅限架构” 4.单机下一步完成 二.sql文件的......
  • 图论——树上问题 学习笔记
    图论——树上问题学习笔记目录树的直径树的重心树的中心经典问题1:最小化最大距离树的直径定义树上任意两节点之间最长的简单路径即为树的直径。显然,一棵树可以有多条直径,他们的长度相等。性质若树上所有边边权均为正,则树的所有直径有交,且中点重合;有树的直径\((p,q......