欢迎莅临 SUN WU GANG 的园子!!!

世上无难事,只畏有心人。有心之人,即立志之坚午也,志坚则不畏事之不成。

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
-------------------------------生成实体类-------------------------------
declare @TableName sysname = 'DictReCheckItem'   
declare @TableNameL sysname = 'DictReCheckItem'
declare @IsCreateControllerMethods  sysname =0
declare @Result varchar(max) = '
/// <summary>
/// ' + @TableName +

'a
/// </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 where;'	  
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)


declare @Controller2 varchar(max) = 
--查询
+'#region query
 /// <summary>
 /// 分页-根据指定条件查询信息
 /// -----------------'
 +@TableName+'Params 对象-----------------
 /// BeginDate--开始日期
 /// EndDate--结束日期
 /// -----------------'
 +@TableName+'Params 对象-----------------
 /// </summary>
 /// <param name="jsonData">'+@TableName+'Params</param>
 ///<param name="pageSize">int型,每页数量</param>
 ///<param name="pageIndex">int型,当前页数</param>
 /// <returns>查询结果信息</returns>
 [HttpGet]
 [Route("api/'+@TableName+'/Get'+@TableName+'")]
 public HttpResponseMessage Get'+@TableName+'(string jsonData, int pageSize, int pageIndex)
 {
     var res = new ProxyResult();
     res.Success = false;
     try
     {
         int totalCount = 0;'
		 +@TableName+'Params mode = JsonHelper.Instance.Deserialize<'+@TableName+'Params>(jsonData);
         List<'+@TableName+'> list = '+@TableName+'Service.Get'+@TableName+'(mode, pageSize, pageIndex, out totalCount);
         res.JsonData = JsonHelper.Instance.Serialize(list);
         res.Success = true;
         res.DataCount = totalCount;
     }
     catch (Exception ex)
     {
         string input = "入参==" + jsonData + "\r\n";
         LogHelper.ErrorFormat("api/'+@TableName+'/Get'+@TableName+' 异常-{0}", input + ex.Message);
         res.ErrMessage = ex.Message;
     }
     HttpResponseMessage result = new HttpResponseMessage
     {
         Content = new StringContent(JsonHelper.Instance.Serialize(res),
         System.Text.Encoding.GetEncoding("UTF-8"), "application/json")
     };//这里是去掉反斜杠再放回出去,json就只剩下双引号。
     return result;
 }

 #endregion'+ char(13)+ char(13)
--删除方法
+'	#region Delete
/// <summary>
 /// 根据ID删除字典信息
 /// </summary>
 /// <param name="ids">编号|数组类型</param>
 /// <returns></returns>
 [HttpGet]' + char(13)
+'[Route("api/'+@TableName+'/DeleteByIds")]'+ char(13)
+'public HttpResponseMessage DeleteByIds(List<string> ids)
{
    var res = new ProxyResult();
    res.Success = false;
    try
    {'
+'res.JsonData = JsonHelper.Instance.Serialize('+ @TableName + 'Service.DeleteByIds(ids));'
+'     res.Success = true;
 }
 catch (Exception ex)
 {'
 +'LogHelper.ErrorFormat("api/'+@TableName+'/DeleteByIds 异常-{0}", ex);'
 +'        res.ErrMessage = ex.Message;
    }
    HttpResponseMessage result = new HttpResponseMessage
    {
        Content = new StringContent(JsonHelper.Instance.Serialize(res),
        System.Text.Encoding.GetEncoding("UTF-8"), "application/json")
    };//这里是去掉反斜杠再放回出去,json就只剩下双引号。
    return result;
}'+char(13) +char(13) 
+'#endregion' +char(13) +char(13) 

--修复更改
+'   #region Update'+char(13) 
     +'   /// <summary>'+char(13) 
	 +'/// 修改 ' + @TableName +char(13) 
+' /// </summary>
 /// <param name="jsdata">'+@TableName+'json</param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/'+@TableName+'/Update")]
        public HttpResponseMessage Update([FromBody] object jsdata)
        {
            var res = new ProxyResult();
            res.Success = false;
            try
            {'
			+@TableName+' obj = JsonHelper.Instance.Deserialize<'+@TableName+'>(jsdata.ToString());
                res.JsonData = JsonHelper.Instance.Serialize('+@TableName+'Service.Update(obj));
                res.Success = true;
            }
            catch (Exception ex)
            {
                LogHelper.ErrorFormat("api/'+@TableName+'/Update 异常-{0}", ex.Message + ex.StackTrace);
                res.ErrMessage = ex.Message;
            }
            HttpResponseMessage result = new HttpResponseMessage
            {
                Content = new StringContent(JsonHelper.Instance.Serialize(res),
                System.Text.Encoding.GetEncoding("UTF-8"), "application/json")
            };//这里是去掉反斜杠再放回出去,json就只剩下双引号。
            return result;
		}'+char(13) +char(13) 
+'#endregion' +char(13) +char(13) 

		
+char(13) +'}'+char(13) 

print @Controller
print @Controller2

declare @Controller3 varchar(max) = ''

print @Controller3



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

  

posted on 2023-10-11 16:51  sunwugang  阅读(4)  评论(0编辑  收藏  举报