<%-- 
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.Data;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using Winson.Framework.DBProviders;
using Winson.Framework.LogProviders;
using Winson.Framework.Utility;
using <%=ProjectName%>.EntityOP.Base;
using <%=ProjectName%>.EntityOP.Entity;
using <%=ProjectName%>.EntityOP.BaseEntityOP;


namespace <%=ProjectName%>.EntityOP
{	
	/// <summary>
	<%if (SourceTable.Description!=""){%>
	///<%=SourceTable.Description%> 实体操作类
	<%}else{%>
    /// <%= SourceTable.Name %> 实体操作类
	<%}%>    
    /// </summary>
	public class <%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>
    {
        #region 私有变量
        List<<%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>DS> _<%= SourceTable.Name.Replace(" ","").ToLower() %>List;
        <%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>DS _<%= SourceTable.Name.Replace(" ","").ToLower() %>DS;
        <%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>OP _op;
        int _count;
        string _cacheKey="<%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>Count";
        string _cacheCriteria = "<%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>CacheCriteria";
        #endregion

        #region 构造函数
        public <%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>()
        {
            _op = new  <%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>OP();
            _<%= SourceTable.Name.Replace(" ","").ToLower() %>DS = new  <%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>DS();
            _<%= SourceTable.Name.Replace(" ","").ToLower() %>List = new List< <%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>DS>();
        }
        #endregion

		#region 定义事件
        public event OPEventHandler<<%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>> OnAdded;
        public event OPEventHandler<<%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>> OnBatchAdded;
        public event OPEventHandler<<%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>> OnUpdated;
        public event OPEventHandler<<%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>> OnBatchUpdated;
        public event OPEventHandler<<%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>> OnDeleted;
        public event OPEventHandler<<%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>> OnBatchDeleted;
        #endregion

        #region 实体操作
        /// <summary>
        /// 获取实体
        /// </summary>
        public <%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>DS Entity
        {
            get { return _<%= SourceTable.Name.Replace(" ","").ToLower() %>DS; }
			set { _<%= SourceTable.Name.Replace(" ","").ToLower() %>DS = value; }
        }
        /// <summary>
        /// 获取总记录数
        /// </summary>
        /// <returns>记录数</returns>
        public int Count()
        {
            return Count(" 1=1 ");
        }
        /// <summary>
        /// 获取条件记录数
        /// </summary>
        /// <param name="criteria">查询条件</param>
        /// <returns>记录数</returns>
        public int Count(string criteria)
        {
            object _co = CacheHelper.Get(_cacheKey);
            object _cre = CacheHelper.Get(_cacheCriteria);
            if (_co == null || (_co != null && criteria != _cre.ToString()))
            {
                NameValueCollection conditionValue = new NameValueCollection();
                conditionValue["where"] = criteria;
                _count = _op.GetList(conditionValue).Count;

                CacheHelper.Insert(_cacheKey, _count);
                CacheHelper.Insert(_cacheCriteria, criteria);
            }
            else
                _count = Convert.ToInt32(_co);

            return _count;
        }
        /// <summary>
        /// 创建新的实体
        /// </summary>
        public void CreateEntity()
        {
            _<%= SourceTable.Name.Replace(" ","").ToLower() %>DS = new <%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>DS();
        }
        /// <summary>
        /// 追加实体到集合，以便批量操作
        /// </summary>
        public void AppendEntity()
        {
            _<%= SourceTable.Name.Replace(" ","").ToLower() %>List.Add(_<%= SourceTable.Name.Replace(" ","").ToLower() %>DS);
        }
        #endregion        

        #region 查询操作
        /// <summary>
        /// 获取实体集合
        /// </summary>
        /// <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) 
        {
            return _op.GetList(conditionValue);
        }
        /// <summary>
        /// 分页获取实体集合
        /// </summary>
        /// <param name="limit">每页显示记录数</param>
        /// <param name="currpage">当前页数</param>
        /// <param name="criteria">查询条件,null为查询所有</param>
        /// <param name="orderby">排序字段</param>
        /// <param name="order">排序方式，默认为 ASC</param>
        /// <returns>实体集合</returns>
        public List<<%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>DS> GetList(int limit, int currpage, string criteria, string orderby, string order)
        {            
            NameValueCollection paramValue = new NameValueCollection();
            paramValue["sql"] = _op.GeneratePagerSql("<%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>", limit, currpage, criteria, orderby, order);
            return _op.GetList(paramValue);
        }
        /// <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)
        {
            return _op.GetEntity(conditionValue);
        }
        /// <summary>
        /// 从实体集合中获取单个实体
        /// </summary>
        /// <param name="entityList">实体集合</param>
        /// <param name="fieldID">实体ID</param>
        /// <returns>实体</returns>
        public <%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>DS GetEntity(IList entityList, int fieldID)
        {
            return _op.GetEntity(entityList, fieldID);
        }
        /// <summary>
        /// 获取实体，返回DataSet
        /// </summary>
        /// <param name="conditionValue">条件参数，如键名为"sql"，则为自定义条件;如为NULL则获取所有实体</param>
        /// <returns>DataSet数据</returns>
        public DataSet GetDataSet(NameValueCollection conditionValue)
        {
            return _op.GetDataSet(conditionValue);
        }
        #endregion

        #region 单实体操作
		/// <summary>
        /// 添加实体
        /// </summary>
        /// <returns>影响记录数</returns>
        public int Add()
        {
            return Add(null);
        }
        /// <summary>
        /// 添加实体
        /// </summary>
        /// <returns>影响记录数</returns>
        public int Add(string customParm)
        {
			CacheHelper.Remove(_cacheKey);
            int result = _op.Add(_<%= SourceTable.Name.Replace(" ","").ToLower() %>DS);
			if (OnAdded != null)
            {
                if (result > 0)
				{
					_<%= SourceTable.Name.Replace(" ","").ToLower() %>DS.<%= ConvertToPascal(SourceTable.PrimaryKey.MemberColumns[0].Name) %> = _op.GetMaxID() - 1;
                    OnAdded(this, new OPEvent(customParm, _<%= SourceTable.Name.Replace(" ","").ToLower() %>DS));
				}
                else
                    OnAdded(this, new OPEvent(0));
            }
             if (result > 0)
                return _op.GetMaxID() - 1;
            else 
                return result;
        }
        /// <summary>
        /// 更新实体，直接根据实体主键更新
        /// </summary>
        /// <returns>影响记录数</returns>
        public int Update()
        {
            return this.Update(null);
        }
        /// <summary>
        /// 更新实体，根据输入条件更新
        /// </summary>
        /// <param name="conditionValue">
		///	条件参数，有以下2种：
		///	1.如键名为"sql"，则为完整的自定义sql语句
		///	2.如键名为"where"，则为自定义条件（已包括where）;			
		///	</param>
        /// <returns>影响记录数</returns>
        public int Update(NameValueCollection conditionValue)
        {
            int result = _op.Update(_<%= SourceTable.Name.Replace(" ","").ToLower() %>DS, conditionValue);
			if (OnUpdated != null)
            {
                if (result > 0)
                    OnUpdated(this, new OPEvent(_<%= SourceTable.Name.Replace(" ","").ToLower() %>DS.<%= ConvertToPascal(SourceTable.PrimaryKey.MemberColumns[0].Name) %>));
                else
                    OnUpdated(this, new OPEvent(0));
            }
            return result;
        }
        /// <summary>
        /// 删除实体，直接根据实体主键删除
        /// </summary>
        /// <returns>影响记录数</returns>
        public int Delete()
        {
			int result = 0;
            if (_<%= SourceTable.Name.Replace(" ","").ToLower() %>DS.<%= ConvertToPascal(SourceTable.PrimaryKey.MemberColumns[0].Name) %> > 0)
            {
				CacheHelper.Remove(_cacheKey);
                NameValueCollection conditionValue = new NameValueCollection();
                conditionValue["<%= ConvertToPascal(SourceTable.PrimaryKey.MemberColumns[0].Name) %>"] = _<%= SourceTable.Name.Replace(" ","").ToLower() %>DS.<%= ConvertToPascal(SourceTable.PrimaryKey.MemberColumns[0].Name) %>.ToString();
                result = this.Delete(conditionValue);
            }
            if (OnDeleted != null)
            {
                if (result > 0)
                    OnDeleted(this, new OPEvent(_<%= SourceTable.Name.Replace(" ","").ToLower() %>DS.<%= ConvertToPascal(SourceTable.PrimaryKey.MemberColumns[0].Name) %>));
                else
                    OnDeleted(this, new OPEvent(0));
            }
            return result; 
        }
        /// <summary>
        /// 删除实体，根据输入条件删除
        /// </summary>
        /// <param name="conditionValue">
		///	条件参数，有以下2种：
		///	1.如键名为"sql"，则为完整的自定义sql语句
		///	2.如键名为"where"，则为自定义条件（已包括where）;			
		///	</param>      
        /// <returns>影响记录数</returns>
        public int Delete(NameValueCollection conditionValue)
        {
			int result = 0;
			if (conditionValue != null)
			{
				CacheHelper.Remove(_cacheKey);
				result = _op.Delete(conditionValue);
			}
			if (OnDeleted != null)
            {
                if (result > 0)
                    OnDeleted(this, new OPEvent(_<%= SourceTable.Name.Replace(" ","").ToLower() %>DS.<%= ConvertToPascal(SourceTable.PrimaryKey.MemberColumns[0].Name) %>));
                else
                    OnDeleted(this, new OPEvent(0));
            }
            return result;
        }
        #endregion

        #region 批量操作

        /// <summary>
        /// 批量添加实体
        /// </summary>
        /// <returns>成功返回True 否则返回False</returns>
        public bool AddBatch()
        {
			bool result = false;
			if (_<%= SourceTable.Name.Replace(" ","").ToLower() %>List.Count > 0)
			{
				CacheHelper.Remove(_cacheKey);
            	result = _op.AddBatch(_<%= SourceTable.Name.Replace(" ","").ToLower() %>List);
			}
			if (OnBatchAdded != null)
            {
                if (result)
                {
                    string bid = string.Empty;
                    foreach (<%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>DS ds in _<%= SourceTable.Name.Replace(" ","").ToLower() %>List)
                        bid += ds.<%= ConvertToPascal(SourceTable.PrimaryKey.MemberColumns[0].Name) %>.ToString() + ",";
                    OnBatchAdded(this, new OPEvent(bid.Substring(0, bid.Length - 1)));
                }
                else
                    OnBatchAdded(this, new OPEvent(null));
            }
            return result;
        }

        /// <summary>
        /// 批量更新实体
        /// </summary>
        /// <returns>成功返回True 否则返回False</returns>
        public bool UpdateBatch()
        {
			bool result = false;
            if (_<%= SourceTable.Name.Replace(" ","").ToLower() %>List.Count > 0)
            {
				CacheHelper.Remove(_cacheKey);
            	result = _op.UpdateBatch(_<%= SourceTable.Name.Replace(" ","").ToLower() %>List);
            }
			if (OnBatchUpdated != null)
            {
                if (result)
                {
                    string bid = string.Empty;
                    foreach (<%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>DS ds in _<%= SourceTable.Name.Replace(" ","").ToLower() %>List)
                        bid += ds.<%= ConvertToPascal(SourceTable.PrimaryKey.MemberColumns[0].Name) %>.ToString() + ",";
                    OnBatchUpdated(this, new OPEvent(bid.Substring(0, bid.Length - 1)));
                }
                else
                    OnBatchUpdated(this, new OPEvent(null));
            }
            return result;
        }

        /// <summary>
        /// 批量删除实体
        /// </summary>
        /// <returns>成功返回True 否则返回False</returns>
        public bool DeleteBatch()
        {
			bool result = false;
            if (_<%= SourceTable.Name.Replace(" ","").ToLower() %>List.Count > 0)
            {
				CacheHelper.Remove(_cacheKey);
            	return _op.DeleteBatch(_<%= SourceTable.Name.Replace(" ","").ToLower() %>List);
			}
			if (OnBatchDeleted != null)
            {
                if (result)
                {
                    string bid = string.Empty;
                    foreach (<%= ConvertToPascal(SourceTable.Name.Replace(" ","")) %>DS ds in _<%= SourceTable.Name.Replace(" ","").ToLower() %>List)
                        bid += ds.<%= ConvertToPascal(SourceTable.PrimaryKey.MemberColumns[0].Name) %>.ToString() + ",";
                    OnBatchDeleted(this, new OPEvent(bid.Substring(0, bid.Length - 1)));
                }
                else
                    OnBatchDeleted(this, new OPEvent(null));
            }
            return result;
        }
        #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>

