动软根据MySQL数据库生成C#.NET DAL数据层模版代码

<#@ template language="c#" HostSpecific="True" #>
<#@ output extension= ".cs" #>
<#
	int searchColumn=0;
	TableHost host = (TableHost)(Host);	
	host.NameSpace = "CoalDAL";
	string ModelSpace = "UserInfo";
	string DbParaHead=host.DbParaHead;
	string DbParaDbType=host.DbParaDbType;
	string preParameter=host.preParameter;
	ColumnInfo identityKey=host.IdentityKey;
	string returnValue = "void";
    if (identityKey!=null)
    {         
         returnValue = CodeCommon.DbTypeToCS(identityKey.TypeName);              
    }
#>

/*
 * Copyright (C)  
 * All rights reserved 
 * 文件摘要:
 * 当前版本:  
 * 编写日期: 
 * 设    计: 
 * 编 写 人:  
 * 修改记录: 
 */
 
using System;
using System.Text;
using System.Collections.Generic;
using System.Data;
using MySql.Data.MySqlClient;
using Common.Utility;
using Common.MySqlDBUtility;
using CoalModel;
using Common.Log;

namespace <#= host.NameSpace #> 
<# if( host.Folder.Length > 0){ #>
	.<#= host.Folder #>
<# } #>
{
	<# if( host.TableDescription.Length > 0) {#>
 	//<#= host.TableDescription #>
	<# } #>
public partial class <#= ModelSpace #>DAL:DalBase
	{
	     #region  公共方法
   		/// <summary>
   		/// 判断表第几列的数据是否存在,如需要调整列数请修改模版头
   		/// </summary>
   		/// <param name="<#= host.Fieldlist[searchColumn].ColumnName #>"></param>
   		/// <returns></returns>    
		public bool Exists(string <#= host.Fieldlist[searchColumn].ColumnName #>)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select count(0) from <#= host.TableName #>");
			strSql.Append(" where ");
            strSql.Append(" <#= host.Fieldlist[searchColumn].ColumnName #> = '"+<#=host.Fieldlist[searchColumn].ColumnName#>+"';");
            try
            {
				return int.Parse(SqlHelper.ExecuteScalar(ConnectionString, CommandType.Text, strSql.ToString(), null).ToString()) > 0;
			}
            catch (Exception ex)
            {
                LogWriter.Write(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.FullName + "." + new System.Diagnostics.StackTrace().GetFrame(0).GetMethod().Name + "()");
                return false;
            }
		}
		
				
		
		/// <summary>
        /// 增加一条数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
		public int Add(<#= ModelSpace #> model, bool isTransaction=false)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("insert into <#= host.TableName #>(");			
            strSql.Append("<# for(int i=1;i< host.Fieldlist.Count;i++) {   ColumnInfo c = host.Fieldlist[i]; if (!c.IsIdentity) {#><#= c.ColumnName#><# if (i< host.Fieldlist.Count-1 ) {#>,<#}#><#}}#>");
			strSql.Append(") values (");
            strSql.Append("<# for(int i=1;i< host.Fieldlist.Count;i++) {   ColumnInfo c = host.Fieldlist[i]; if (!c.IsIdentity) {#><#=preParameter#><#= c.ColumnName#><# if (i< host.Fieldlist.Count-1 ) {#>,<#}#><#}}#>");            
            strSql.Append(") ");            
            strSql.Append(";select @@IDENTITY;");
			MySqlParameter[] parameters = {
			<# for(int i=1;i< host.Fieldlist.Count;i++)
            {   
            ColumnInfo c = host.Fieldlist[i];
            if(c.IsIdentity) continue;
            #>
            new MySqlParameter("<#=preParameter#><#=c.ColumnName#>", MySqlDbType.<#=CodeCommon.DbTypeLength(host.DbType, c.TypeName, c.Length)#>) <# if (i< host.Fieldlist.Count-1 ) {#>,<#}#>            
            <# }#>  
            };
			<# for(int i=1;i< host.Fieldlist.Count;i++){ ColumnInfo c = host.Fieldlist[i]; #>            
            parameters[<#= i-1 #>].Value = <# if ("uniqueidentifier" == c.TypeName.ToLower()){#>Guid.NewGuid();<#} else {#>model.<#=c.ColumnName#>;<#} #>
            <# }#>
              
			object obj;
            try
            {
                if (isTransaction)
                {
                    obj = SqlHelper.ExecuteScalar(MySqlConn, CommandType.Text, strSql.ToString(), parameters);
                }
                else
                {
                    obj = SqlHelper.ExecuteScalar(ConnectionString, CommandType.Text, strSql.ToString(), parameters);
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.ToLower().Contains("duplicate"))
                {
                    return 0;
                }
                else
                {
                    LogWriter.Write(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.FullName + "." + new System.Diagnostics.StackTrace().GetFrame(0).GetMethod().Name + "()");
                    return -1;
                }
            }

            if (obj == null)
            {
                return -1;
            }
            else
            {
                return Convert.ToInt32(obj);
            }			
		}
		
		
		/// <summary>
		/// 更新一条数据
		/// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
		public int Update(<#= ModelSpace #> model, bool isTransaction = false)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("update <#= host.TableName #> set ");
			<# for(int i=0;i< host.Fieldlist.Count;i++)
            {   ColumnInfo c = host.Fieldlist[i]; #>
            <# if (!c.IsIdentity) {#>            
            strSql.Append(" <#= c.ColumnName #> = <#=preParameter#><#=c.ColumnName#> <# if (i< host.Fieldlist.Count-1 ) {#>,<#}#> ");<# }#>
            <# }#>			
			strSql.Append(" where <#= CodeCommon.GetWhereParameterExpression(host.Keys, true ,host.DbType) #> ");
						
MySqlParameter[] parameters = {
			<# for(int i=0;i< host.Fieldlist.Count;i++)
            {   ColumnInfo c = host.Fieldlist[i]; #>
            new MySqlParameter("<#=preParameter#><#=c.ColumnName#>", MySqlDbType.<#=CodeCommon.DbTypeLength(host.DbType, c.TypeName, c.Length)#>) <# if (i< host.Fieldlist.Count-1 ) {#>,<#}#>
            
            <# }#>  
            };
			<# n=0; #>
			<# foreach (ColumnInfo c in host.Fieldlist) { #>            
            parameters[<#= n #>].Value = model.<#=c.ColumnName#>;<# n=n+1; #>
            <# }#>
            
            int rows;
            try
            {
                 if (isTransaction)
                {
                    rows = SqlHelper.ExecuteNonQuery(MySqlConn, CommandType.Text, strSql.ToString(), parameters);
                }
                else
                {
                    rows = SqlHelper.ExecuteNonQuery(ConnectionString, CommandType.Text, strSql.ToString(), parameters);
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.ToLower().Contains("duplicate"))
                {
                    return -2;
                }
                else
                {
                    LogWriter.Write(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.FullName + "." + new System.Diagnostics.StackTrace().GetFrame(0).GetMethod().Name + "()");
                    return -1;
                }
            }
            return rows;
		}
		
		
		/// <summary>
		/// 删除一条数据
		/// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
		public bool Delete(<#=CodeCommon.GetInParameter(host.Keys, true)#>,bool isTransaction = false)
		{
			
			StringBuilder strSql=new StringBuilder();
			strSql.Append("delete from <#= host.TableName #> ");
			strSql.Append(" where <#= CodeCommon.GetWhereParameterExpression(host.Keys, true, host.DbType)#>");
			<#= CodeCommon.GetPreParameter(host.Keys, true, host.DbType) #>

			int rows;
			try
            {
				if (isTransaction)
                {
                    rows = SqlHelper.ExecuteNonQuery(MySqlConn, CommandType.Text, strSql.ToString(), parameters);
                }
                else
                {
                    rows = SqlHelper.ExecuteNonQuery(ConnectionString, CommandType.Text, strSql.ToString(), parameters);
                }
			}
            catch (Exception ex)
            {
                LogWriter.Write(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.FullName + "." + new System.Diagnostics.StackTrace().GetFrame(0).GetMethod().Name + "()");
                return false;
            }
			if (rows > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		
	 
		
		 
		/// <summary>
		/// 得到一个对象实体
		/// </summary>
		public <#= ModelSpace #>  GetModelByRow(DataRow row)
		{
		    <#=ModelSpace#> model=new <#=ModelSpace#>();
		    <# foreach (ColumnInfo c in host.Fieldlist) { #>
				<# if(CodeCommon.DbTypeToCS(c.TypeName)=="int"||
				CodeCommon.DbTypeToCS(c.TypeName)=="long"||
				CodeCommon.DbTypeToCS(c.TypeName)=="float"||
				CodeCommon.DbTypeToCS(c.TypeName)=="DateTime"||
				CodeCommon.DbTypeToCS(c.TypeName)=="decimal")
				{#>
				try
				{
				if(row["<#=c.ColumnName#>"].ToString()!="")
				{
					model.<#=c.ColumnName#>=<#=CodeCommon.DbTypeToCS(c.TypeName)#>.Parse(row["<#=c.ColumnName#>"].ToString());
				}
				}
				catch (Exception ex){}
				<# } #>
				<# if(CodeCommon.DbTypeToCS(c.TypeName)=="string") {#>
				try
				{
				model.<#=c.ColumnName#>= row["<#=c.ColumnName#>"].ToString();
				}
				catch (Exception ex){}
				<# } #>
				<# if(CodeCommon.DbTypeToCS(c.TypeName)=="byte[]") {#>
				try
				{
				if(row["<#=c.ColumnName#>"].ToString()!="")
				{
					model.<#=c.ColumnName#>= (byte[])row["<#=c.ColumnName#>"];
				}
				}
				catch (Exception ex){}
				<# } #>
				<# if(CodeCommon.DbTypeToCS(c.TypeName)=="Guid") {#>
				try
				{
				if(row["<#=c.ColumnName#>"].ToString()!="")
				{
					model.<#=c.ColumnName#>= row["<#=c.ColumnName#>"].ToString();
				}
				}
				catch (Exception ex){}
				<# } #>
				<# if(CodeCommon.DbTypeToCS(c.TypeName)=="bool") {#>
				try
				{
				if(row["<#=c.ColumnName#>"].ToString()!="")
				{
					if((row["<#=c.ColumnName#>"].ToString()=="1")||(row["<#=c.ColumnName#>"].ToString().ToLower()=="true"))
					{
					model.<#=c.ColumnName#>= true;
					}
					else
					{
					model.<#=c.ColumnName#>= false;
					}
				}
				}
				catch (Exception ex){}
				<# } #>
				<# } #>						
				return model;
		}
		
		/// <summary>
		/// 得到一个对象实体
		/// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
		public <#= ModelSpace #> GetModel(<#= CodeCommon.GetInParameter(host.Keys,true) #>)
		{
			
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select <# for(int i=0;i< host.Fieldlist.Count;i++) { #><#= host.Fieldlist[i].ColumnName #><# if(i< host.Fieldlist.Count-1 ) {#>,<# } #> <#}#> ");			
			strSql.Append("  from <#= host.TableName #> ");
			strSql.Append(" where <#= CodeCommon.GetWhereParameterExpression(host.Keys, true, host.DbType) #>");
			<#=CodeCommon.GetPreParameter(host.Keys, true, host.DbType)#>
			
			<#=ModelSpace#> model=new <#=ModelSpace#>();
			DataSet ds;
			try
			{
				ds=SqlHelper.ExecuteDataSet(ConnectionString, CommandType.Text, strSql.ToString(), parameters);
			}
			catch (Exception ex)
            {
                LogWriter.Write(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.FullName + "." + new System.Diagnostics.StackTrace().GetFrame(0).GetMethod().Name + "()");
                return null;
            }
			if(ds.Tables[0].Rows.Count>0)
			{
				 		
				return GetModelByRow(ds.Tables[0].Rows[0]);
			}
			else
			{
				return null;
			}
		}
		
		 
		 public List<<#= ModelSpace #>>  GetListByTable(DataTable dt)
        {
        	List<<#= ModelSpace #>> list = new List<<#= ModelSpace #>>();
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    list.Add(GetModelByRow(dt.Rows[i]));
                }
            }
            return list;
        }
		
		/// <summary>
        /// 获得数据列表
        /// </summary>
        /// <param name="strWhere"></param>
        /// <returns></returns>
		public DataSet GetList(string strWhere, params MySqlParameter[] cmdParms)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select * ");
			strSql.Append(" FROM <#= host.TableName #> ");
			if(strWhere.Trim()!="")
			{
				strSql.Append(" where "+strWhere);
			}
			try
			{
				return SqlHelper.ExecuteDataSet(ConnectionString, CommandType.Text, strSql.ToString(), cmdParms);
			}
			catch (Exception ex)
            {
                LogWriter.Write(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.FullName + "." + new System.Diagnostics.StackTrace().GetFrame(0).GetMethod().Name + "()");
                return null;
            }
		}
		
		/// <summary>
        /// 获取记录总数
        /// </summary>
        /// <param name="strWhere"></param>
        /// <returns></returns>
        public int GetRecordCount(string strWhere, params MySqlParameter[] cmdParms)
        {
            try
            {
                StringBuilder strSql=new StringBuilder();
                strSql.Append("select count(0) from <#= host.TableName #> where 1=1 ");
                if (strWhere.Trim() != "")
                {
                    strSql.Append(strWhere);
                }
                strSql.Append(";");
                object obj = SqlHelper.ExecuteScalar(ConnectionString, CommandType.Text, strSql.ToString(),cmdParms);
                if (obj == null)
                {
                    return 0;
                }
                else
                {
                    return Convert.ToInt32(obj);
                }

            }
            catch (Exception ex)
            {
                LogWriter.Write(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.FullName + "." + new System.Diagnostics.StackTrace().GetFrame(0).GetMethod().Name + "()");
                return 0;
            }
        }
        /// <summary>
        /// 分页获取数据列表
        /// </summary>
        public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int pageSize,out int total, params MySqlParameter[] cmdParms)
        {
        	total = 0;
            StringBuilder strSql=new StringBuilder();
            strSql.Append("select * from <#= host.TableName #> where 1=1 ");
            if (strWhere.Trim() != "")
            {
                 strSql.Append(strWhere);
            }
            if (!string.IsNullOrEmpty(orderby.Trim()))
            {
                strSql.Append(" order by " + orderby);
            }
            else
            {
                strSql.Append(" order by id desc");
            }
            strSql.Append(" LIMIT "+startIndex+","+pageSize+";");
            try
            {
            	total = GetRecordCount(strWhere);
                return SqlHelper.ExecuteDataSet(ConnectionString, CommandType.Text, strSql.ToString(),cmdParms);
            }
            catch (Exception ex)
            {
                LogWriter.Write(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.FullName + "." + new System.Diagnostics.StackTrace().GetFrame(0).GetMethod().Name + "()");
                return null;
            }
        }
        #endregion Model
	}
}

<#+
int n=0;
#>



© 2016-2024 阿尔佛 aerfo.com | 豫ICP备17044542号 | 豫公网安备 41010602000172