<%-- 
Name:Winson.Entity
Author: winson
Ver:3.3
Description: 实体类代码生成
--%>
<%@ CodeTemplate Language="C#" TargetLanguage="C#" Debug="False" Description="Create a list of properties from database table." ResponseEncoding="UTF-8"%>
<%@ Property Name="SourceDatabase" Type="SchemaExplorer.DatabaseSchema" Category="数据库" Description="连接数据库对象." %>
<%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Category="表名" Description="数据源表" %>
<%@ Property Name="ProjectName" Type="System.String" Default="Winson" Optional="False" Category="项目名称" Description="项目名称" %>
<%@ Map Name="CSharpAlias" Src="System-CSharpAlias" Description="可获取数据类型" %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
//=============================================================================
// This project was built by Winson.Framework 3.3
//
// Copyright (c) 2007-2009 Winson 
//
// Create Date: <%= DateTime.Now.ToString() %>
//=============================================================================

using System;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using Winson.Framework.DBProviders;
using Winson.Framework.LogProviders;
using <%=ProjectName%>.EntityOP.Base;
using <%=ProjectName%>.EntityOP.Entity;

namespace <%=ProjectName%>.EntityOP.BaseEntityOP
{	
	/// <summary>
    /// <%= SourceTable.Name %>实体操作类
    /// </summary>
	public class <%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>OP : BaseOP
    {
        #region 私有变量
        List<<%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>DS> <%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>List;
        <%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>DS <%= SourceTable.Name.Replace(" ","").ToLower() %>DS;
        ArrayList fieldName;
        ArrayList fieldValue;
        List<ArrayList> fieldNameList;
        List<ArrayList> fieldValueList;
        #endregion

        #region 构造函数
        public <%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>OP()
        {
            _tableName = "<%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>";
            sql = "select * from " + _tableName;
            _primekey = GetPrimeKey();
        }
        #endregion              

        #region 查询操作
        /// <summary>
        /// 获取实体集合
        /// </summary>
        /// <param name="conditionValue">条件参数，如键名为"sql"，则为自定义条件;如为NULL则获取所有实体</param>
        /// <param name="conditionValue">
		///	条件参数，有以下3种：
		///	1.如为NULL则获取所有实体
		///	2.如键名为"sql"，则为完整的自定义sql语句
		///	3.如键名为"where"，则为自定义条件（已包括where）;			
		///	</param>
        /// <returns>实体集合</returns>
        public List<<%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>DS> GetList(NameValueCollection conditionValue) 
        {
            try
            {
                <%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>List = new List<<%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>DS>();
                //将数据填充到实体集合
                DbDataReader dr = null;
                dr = DBManage.ExecuteReader(DBManage.Conn, sql, conditionValue);
                if (dr != null)
                {
					while (dr.Read())
					{
						<%= SourceTable.Name.Replace(" ","").ToLower() %>DS = new <%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>DS();
						FillDS(<%= SourceTable.Name.Replace(" ","").ToLower() %>DS, dr);
						<%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>List.Add(<%= SourceTable.Name.Replace(" ","").ToLower() %>DS);
					}
                }
                return <%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>List;
            }
            catch (Exception e)
            {
                LogManage.OutputErrLog(e, new Object[] { conditionValue });
                return null;
            }
            finally
            {
                DBManage.Conn.Close();
            }
        }
        /// <summary>
        /// 从数据库中获取单个实体
        /// </summary>       
        /// <param name="conditionValue">
		///	条件参数，有以下3种：
		///	1.如为NULL则获取最后一个新增的实体
		///	2.如键名为"sql"，则为完整的自定义sql语句
		///	3.如键名为"where"，则为自定义条件（已包括where）;			
		///	</param>
        /// <returns>实体</returns>
        public <%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>DS GetEntity(NameValueCollection conditionValue)
        {
            DbDataReader dr = null;
            try
            {   
				 string tSql = string.Empty;
                if (conditionValue == null)
                {
                    tSql = DBManage.GenerateGetOneEntitySql(_tableName, _primekey);
                    dr = DBManage.ExecuteReader(DBManage.Conn, tSql, conditionValue);
                }
                else
                    dr = DBManage.ExecuteReader(DBManage.Conn, sql, conditionValue);
                
                if (dr != null && dr.Read())
                {
                    <%= SourceTable.Name.Replace(" ","").ToLower() %>DS = new <%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>DS();
                    FillDS(<%= SourceTable.Name.Replace(" ","").ToLower() %>DS, dr);
                    return <%= SourceTable.Name.Replace(" ","").ToLower() %>DS;
                }
                else
                    return null;
            }
            catch (Exception e)
            {
                LogManage.OutputErrLog(e, new Object[] { conditionValue });
                return null;
            }
            finally
            {
                if(dr!=null)   dr.Close();
                DBManage.Conn.Close();
            }
        }
        /// <summary>
        /// 从实体集合中获取单个实体
        /// </summary>
        /// <param name="entityList">实体集合</param>
        /// <param name="fieldID">实体ID</param>
        /// <returns>实体</returns>
        public <%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>DS GetEntity(IList entityList, int fieldID)
        {
            try
            {
                foreach (<%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>DS <%= SourceTable.Name.Replace(" ","").ToLower() %>_DS in entityList)
                {
                    if (<%= SourceTable.Name.Replace(" ","").ToLower() %>_DS.<%= ConvertToPascal(SourceTable.PrimaryKey.MemberColumns[0].Name) %> == fieldID)
                        return <%= SourceTable.Name.Replace(" ","").ToLower() %>_DS;
                }
                return null;
            }
            catch (Exception e)
            {
                LogManage.OutputErrLog(e, new Object[] { entityList, fieldID });
                return null;
            }
        }
        #endregion

        #region 单实体操作
        /// <summary>
        /// 添加实体
        /// </summary>
        /// <param name="ds">实体</param>
        /// <returns>影响记录数</returns>
        public int Add(<%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>DS ds)
        {
            try
            {
                fieldName = new ArrayList();
                fieldValue = new ArrayList();
                int maxID = GetMaxID();
                if (maxID == 0) return 0;
                for (int i = 0; i < ds.Count; i++)
                {
                    if (ds[i, 1, maxID] != null)
                    {
                        fieldName.Add(ds[i, 1, maxID]);
                        fieldValue.Add(ds[i, 0, maxID]);
                    }
                }
                return DBManage.ExecuteNonQuery(DBAction.Insert, _tableName, fieldName, fieldValue);
            }
            catch (Exception e)
            {
                LogManage.OutputErrLog(e, new Object[] { ds });
                return 0;
            }
        }
        /// <summary>
        /// 更新实体
        /// </summary>
        /// <param name="ds">实体</param>        
        /// <param name="conditionValue">
		///	条件参数，有以下2种：
		///	1.如键名为"sql"，则为完整的自定义sql语句
		///	2.如键名为"where"，则为自定义条件（已包括where）;			
		///	</param>
        /// <returns>影响记录数</returns>
        public int Update(<%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>DS ds, NameValueCollection conditionValue)
        {
            try
            {
                fieldName = new ArrayList();
                fieldValue = new ArrayList();
                for (int i = 0; i < ds.Count; i++)
                {
                    if (ds[i, 1, 0] != null)
                    {
                        fieldName.Add(ds[i, 1, 0]);
                        fieldValue.Add(ds[i, 0, 0]);
                    }
                }
                return DBManage.ExecuteNonQuery(DBAction.Update, _tableName, fieldName, fieldValue, conditionValue);
            }
            catch (Exception e)
            {
                LogManage.OutputErrLog(e, new Object[] { ds, conditionValue });
                return 0;
            }
        }
        /// <summary>
        /// 删除实体
        /// </summary>        
        /// <param name="conditionValue">
		///	条件参数，有以下2种：
		///	1.如键名为"sql"，则为完整的自定义sql语句
		///	2.如键名为"where"，则为自定义条件（已包括where）;			
		///	</param>
        /// <returns>影响记录数</returns>
        public int Delete(NameValueCollection conditionValue)
        {
            try
            {
                return DBManage.ExecuteNonQuery(DBAction.Delete, _tableName, null, null, conditionValue);
            }
            catch (Exception e)
            {
                LogManage.OutputErrLog(e, new Object[] { conditionValue });
                return 0;
            }
        }
        #endregion

        #region 批量操作

        /// <summary>
        /// 批量添加实体
        /// </summary>
        /// <param name="dsList">实体集合</param>
        /// <returns>成功返回True 否则返回False</returns>
        public bool AddBatch(List<<%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>DS> dsList)
        {
            try
            {                
                fieldNameList = new List<ArrayList>();
                fieldValueList = new List<ArrayList>();
                int maxID = GetMaxID();
                if (maxID == 0) return false;
                
                dsList.ForEach(
					delegate(<%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>DS ds)               
						{
							fieldName = new ArrayList();
							fieldValue = new ArrayList();
							for (int n = 0; n < ds.Count; n++)
							{
								if (ds[n, 1, maxID] != null)
								{
									fieldName.Add(ds[n, 1, maxID]);
									fieldValue.Add(ds[n, 0, maxID]);
								}
							}
							maxID++;
							fieldNameList.Add(fieldName);
							fieldValueList.Add(fieldValue);
						}
				);
                return DBManage.ExecuteBatch(DBAction.Insert, _tableName, fieldNameList, fieldValueList);
            }
            catch (Exception e)
            {
                LogManage.OutputErrLog(e, new Object[] { dsList });
                return false;
            }
        }

        /// <summary>
        /// 批量更新实体
        /// </summary>
        /// <param name="dsList">实体集合</param>
        /// <returns>成功返回True 否则返回False</returns>
        public bool UpdateBatch(List<<%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>DS> dsList)
        {
            try
            {
                fieldNameList = new List<ArrayList>();
                fieldValueList = new List<ArrayList>();

                dsList.ForEach(
					delegate(<%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>DS ds) 
					{
						if (ds[0, 1, 0] != null)
						{
							fieldName = new ArrayList();
							fieldValue = new ArrayList();
							for (int n = 0; n < ds.Count; n++)
							{
								if (ds[n, 1, 0] != null)
								{
									fieldName.Add(ds[n, 1, 0]);
									fieldValue.Add(ds[n, 0, 0]);
								}
							}
							fieldNameList.Add(fieldName);
							fieldValueList.Add(fieldValue);
						}
						else
							throw new Exception("主键值未设置，不能进行批量更新操作！主键必须为第一个字段");
					}
                );
                return DBManage.ExecuteBatch(DBAction.Update, _tableName, fieldNameList, fieldValueList);
            }
            catch (Exception e)
            {
                LogManage.OutputErrLog(e, new Object[] { dsList });
                return false;
            }
        }

        /// <summary>
        /// 批量删除实体
        /// </summary>
        /// <param name="dsList">实体集合</param>
        /// <returns>成功返回True 否则返回False</returns>
        public bool DeleteBatch(List<<%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>DS> dsList)
        {
            try
            {
                fieldNameList = new List<ArrayList>();
                fieldValueList = new List<ArrayList>();

                dsList.ForEach(
					delegate(<%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>DS ds) 
					{
						if (ds[0, 1, 0] != null)
						{
							fieldName = new ArrayList();
							fieldValue = new ArrayList();
							for (int n = 0; n < ds.Count; n++)
							{
								if (ds[n, 1, 0] != null)
								{
									fieldName.Add(ds[n, 1, 0]);
									fieldValue.Add(ds[n, 0, 0]);
								}
							}
							fieldNameList.Add(fieldName);
							fieldValueList.Add(fieldValue);
						}
						else
							throw new Exception("主键值未设置，不能进行批量删除操作！主键必须为第一个字段");
					}                
				);				
				return DBManage.ExecuteBatch(DBAction.Delete, _tableName, fieldNameList, fieldValueList);
            }				
            catch (Exception e)
            {
                LogManage.OutputErrLog(e, new Object[] { dsList });
                return false;
            }
        }
        #endregion
    }
}

<script runat="template">
//骆驼命名转换，首字大写
public string ConvertToPascal(string str)
{
	string [] tempStr = str.Split('_');
	string temp="";
	if(tempStr.Length > 0)
	{		
		for(int i=0;i<tempStr.Length;i++)
			temp+=tempStr[i].Substring(0,1).ToUpper()+tempStr[i].Substring(1).ToLower()+"_";
		return temp.Substring(0,temp.Length-1);
	}
	else
    	return str.Substring(0,1).ToUpper() + str.Substring(1).ToLower();
}
</script>

