using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Transactions;
using RFrameGenerate.Model; 
using RFrameGenerate.DAL.Enums;
using RFrameGenerate.DAL.Interface;
using RFrameGenerate.Common;
using RFramework.SQLQuery;
using RFramework.SQLServer;
using RFramework.SQLServer.Enums;

namespace RFrameGenerate.DAL.SQLServer
{
    internal class T_BAS_RecieverAddressDAL : IQuery<T_BAS_RecieverAddress>
    {
        /// <summary>
        /// 事务处理
        /// </summary>
        public SqlRTransaction sqlRTransaction { get; set; }
        
        #region IsExist
        
        /// <summary>
        /// 判断记录是否存在，根据记录的GUID值
        /// </summary>
        /// <param name="dataGuid">待判断的记录的GUID值</param>
        /// <returns>返回判断结果，存在为True，不存在为False</returns>
        public bool IsExist(Guid dataGuid, bool isFilterMerchant = true)
        {
            return IsExist("RecieverAddressGuid", dataGuid,isFilterMerchant);
        } 
        
		/// <summary>
        /// 判断记录是否存在，根据字段名称和字段值
        /// </summary>
        /// <param name="field">字段名称</param>
        /// <param name="value">字段值</param>
        /// <returns>返回判断结果，存在为True，不存在为False</returns>
        public bool IsExist<T>(string field, T value, bool isFilterMerchant = true)
        {
            SqlParameter[] parameters = { 
                                            new SqlParameter("@iCount", SqlDbType.Int),
                                            new SqlParameter("@strField", SqlDbType.NVarChar),
                                            new SqlParameter("@strValue", SqlDbType.NVarChar),
                                            new SqlParameter("@SMerchantGuid", SqlDbType.UniqueIdentifier),
                                            new SqlParameter("@isFilterMerchant", SqlDbType.Bit),
                                        };
            parameters[0].Direction = ParameterDirection.Output;
            parameters[1].Value = field;
            parameters[2].Value = value.ToString();
            parameters[3].Value = CurrentManage.SMerchantGuid;
            parameters[4].Value = isFilterMerchant;
            try
            {
                SqlHelper.ExecuteNonQuery("PT_BAS_RecieverAddress_IsExistGuid", CommandType.StoredProcedure, parameters, sqlRTransaction);
                return parameters[0].Value.ToString() != "0" ? true : false;
            }
            catch (Exception ex)
            {
                Dispose();
                throw new Exception(string.Format("IsExist()参数:strField={0},strValue={1}获取数据出错,异常:{2}", field, value, ex.Message), ex);
            }
        }
         /// <summary>
        /// 判断是否存在
        /// </summary>
        /// <param name="conditionExpression">条件</param>
        /// <returns></returns>
        public bool IsExist(Expression<Func<T_BAS_RecieverAddress, bool>> conditionExpression, bool isFilterNull = false, bool isFilterMerchant = true)
        {
            QueryTranslator where = new QueryTranslator();
            string conditionString = where.Translate(conditionExpression);
            if (isFilterNull == true)
                conditionString = conditionString.SqlFilterNull();
            return IsExist(conditionString,isFilterMerchant);
        }
        /// <summary>
        /// 判断是否存在
        /// </summary>
        /// <param name="conditionString">条件</param>
        /// <returns></returns>
        public bool IsExist(string conditionString, bool isFilterMerchant = true)
        {
            SqlParameter[] parameters = { 
                                            new SqlParameter("@iCount", SqlDbType.Int),
                                            new SqlParameter("@strCondition", SqlDbType.NVarChar),
                                            new SqlParameter("@SMerchantGuid", SqlDbType.UniqueIdentifier),
                                            new SqlParameter("@isFilterMerchant", SqlDbType.Bit),
                                        };
            parameters[0].Direction = ParameterDirection.Output;
            parameters[1].Value = conditionString;
            parameters[2].Value = CurrentManage.SMerchantGuid;
            parameters[3].Value = isFilterMerchant;
            try
            {
                SqlHelper.ExecuteNonQuery("PT_BAS_RecieverAddress_IsExist", CommandType.StoredProcedure, parameters, sqlRTransaction);
                return parameters[0].Value.ToString() != "0" ? true : false;
            }
            catch (Exception ex)
            {
                Dispose();
                throw new Exception(string.Format("IsExist()参数:strCondition={0}获取数据出错,异常:{1}", conditionString, ex.Message), ex);
            }
        }   
        #endregion
		
        #region GetDataByGuid
         
        /// <summary>
        /// 获取一条记录，根据记录的GUID值
        /// </summary>
        /// <param name="dataGuid">待获取的记录的GUID值</param>
        /// <returns>返回指定记录，记录不存在则返回Null</returns>
        public T_BAS_RecieverAddress GetDataByGuid(Guid dataGuid, bool isFilterMerchant = true)
        {
            SqlParameter[] parameters = {
											new SqlParameter("@RecieverAddressGuid", SqlDbType.UniqueIdentifier),
                                            new SqlParameter("@SMerchantGuid", SqlDbType.UniqueIdentifier),
                                            new SqlParameter("@isFilterMerchant", SqlDbType.Bit)
										};
            parameters[0].Value = dataGuid;
            parameters[1].Value = CurrentManage.SMerchantGuid;
            parameters[2].Value = isFilterMerchant;
            
            SqlDataReader dataReader = SqlHelper.ExecuteReader("PT_BAS_RecieverAddress_GetDataByGuid", CommandType.StoredProcedure, parameters, sqlRTransaction);

            T_BAS_RecieverAddress data = null;
            try
            {
                if (dataReader.Read())
                    data = LoadModel(dataReader);
            }
            catch (Exception ex)
            {
                dataReader.Close();
                Dispose();
                throw new Exception(string.Format("GetDataByGuid()参数:dataGuid={0}获取数据出错,异常:{1}", dataGuid, ex.Message), ex);
            }        
                
            dataReader.Close();
             
            return data;
        }
        #endregion
        
        #region Add
        /// <summary>
        /// 批量更新记录集，根据dataList中各个记录的状态
        /// 记录的状态为ToBeAdd的，新增这条记录到数据库
        /// 记录的状态为ToBeDelete的，删除这条记录到数据库
        /// 记录的状态为ToBeUpdate的，更新这条记录到数据库
        /// 记录的状态为Original的，不对这条记录进行任何操作
        /// </summary>
        /// <param name="dataList">待更新的记录集</param>
        /// <returns>返回更新结果，成功为True，失败为False</returns>        
        public void AddList(List<T_BAS_RecieverAddress> dataList)
        {
            bool istran = false;
            if (sqlRTransaction.IsTransaction == false)
            {
                istran = true;
                sqlRTransaction.BeginTransaction();
            }

            DataTable dataListAdd = SqlHelper.GetTables("T_BAS_RecieverAddress",sqlRTransaction);

            
            foreach (var data in dataList)
            {
                DataRow dr = dataListAdd.NewRow();
                if(data.RecieverAddressGuid != null)
    			    dr["RecieverAddressGuid"] = data.RecieverAddressGuid;
                else
                    dr["RecieverAddressGuid"] = DBNull.Value;
                    
                if(data.MemberGuid != null)
    			    dr["MemberGuid"] = data.MemberGuid;
                else
                    dr["MemberGuid"] = DBNull.Value;
                    
                if(data.Reciever != null)
    			    dr["Reciever"] = data.Reciever;
                else
                    dr["Reciever"] = DBNull.Value;
                    
                if(data.Province != null)
    			    dr["Province"] = data.Province;
                else
                    dr["Province"] = DBNull.Value;
                    
                if(data.City != null)
    			    dr["City"] = data.City;
                else
                    dr["City"] = DBNull.Value;
                    
                if(data.Area != null)
    			    dr["Area"] = data.Area;
                else
                    dr["Area"] = DBNull.Value;
                    
                if(data.Address != null)
    			    dr["Address"] = data.Address;
                else
                    dr["Address"] = DBNull.Value;
                    
                if(data.Telephone != null)
    			    dr["Telephone"] = data.Telephone;
                else
                    dr["Telephone"] = DBNull.Value;
                    
                if(data.Zip != null)
    			    dr["Zip"] = data.Zip;
                else
                    dr["Zip"] = DBNull.Value;
                    
                if(data.IsDefualt != null)
    			    dr["IsDefualt"] = data.IsDefualt;
                else
                    dr["IsDefualt"] = DBNull.Value;
                    
                dr["SCreateDate"] = DateTime.Now;
                dr["SCreateUserName"] = CurrentManage.UserName;
                if (data.SMerchantGuid != null && data.SMerchantGuid != Guid.Empty)
                    dr["SMerchantGuid"] = data.SMerchantGuid;
                else
                    dr["SMerchantGuid"] = CurrentManage.SMerchantGuid;
                dataListAdd.Rows.Add(dr);
            }
            
            #region 更新到数据库
            if (dataListAdd.Rows.Count>0)
            { 
            //添加
            SqlHelper.BatchAddData(new DataTable[] { dataListAdd }, sqlRTransaction);
            }
            #endregion

            if (istran == true)
                sqlRTransaction.Commit();

            dataListAdd.Clear();
        }
        /// <summary>
        /// 新增一条记录
        /// </summary>
        /// <param name="data">待新增的记录</param>
        /// <returns>返回新增结果，成功为True，失败为False</returns>
        public void Add(T_BAS_RecieverAddress data)
        {
            SqlParameter[] parameters = {
                                            new SqlParameter("@SCreateDate", SqlDbType.DateTime),
                                            new SqlParameter("@SCreateUserName", SqlDbType.NVarChar),
                                            new SqlParameter("@SMerchantGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@RecieverAddressGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@MemberGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@Reciever", SqlDbType.NVarChar),
											new SqlParameter("@Province", SqlDbType.NVarChar),
											new SqlParameter("@City", SqlDbType.NVarChar),
											new SqlParameter("@Area", SqlDbType.NVarChar),
											new SqlParameter("@Address", SqlDbType.NVarChar),
											new SqlParameter("@Telephone", SqlDbType.NVarChar),
											new SqlParameter("@Zip", SqlDbType.NVarChar),
											new SqlParameter("@IsDefualt", SqlDbType.Bit),
										};
            
            parameters[0].Direction = ParameterDirection.Output;
            parameters[1].Value = CurrentManage.UserName;
            if (data.SMerchantGuid != null && data.SMerchantGuid != Guid.Empty)
                parameters[2].Value = data.SMerchantGuid;
            else
                parameters[2].Value = CurrentManage.SMerchantGuid;
            parameters[3].Value = data.RecieverAddressGuid;
            parameters[4].Value = data.MemberGuid;
            parameters[5].Value = data.Reciever;
            parameters[6].Value = data.Province;
            parameters[7].Value = data.City;
            parameters[8].Value = data.Area;
            parameters[9].Value = data.Address;
            parameters[10].Value = data.Telephone;
            parameters[11].Value = data.Zip;
            parameters[12].Value = data.IsDefualt;
			try
            {
                int rowsAffected = SqlHelper.ExecuteNonQuery("PT_BAS_RecieverAddress_Add", CommandType.StoredProcedure, parameters, sqlRTransaction);
                bool result = rowsAffected != -1 ? true : false;
                if(result == false)
                    throw new Exception("新增数据失败");
            }
            catch(Exception ex)
            {
                Dispose();
                throw new Exception(string.Format("Add()参数:data={0}添加数据出错,异常:{1}", data.ToString(), ex.Message), ex);
            }
        }
        #endregion
        
        #region Top
        /// <summary>
        /// 获取前Top，根据查询条件Lambda表达式及排序字段Lambda表达式、排序方法
        /// </summary>
        /// <param name="conditionExpression">查询条件Lambda表达式</param>
        /// <param name="orderString">排序字段Lambda表达式，字段间用“+”号连接</param>
        /// <param name="orderMethod">排序方法，升序或降序排列</param>
        /// <returns>返回满足条件的记录集</returns>
        public List<T_BAS_RecieverAddress>  GetTopData(string top, Expression<Func<T_BAS_RecieverAddress , bool>> conditionExpression, bool isFilterNull = false, Expression<Func<T_BAS_RecieverAddress , object>> orderExpression = null, OrderMethods orderMethod = OrderMethods.Default, LockType flag = LockType.Default, bool isFilterMerchant = true)
        {
            QueryTranslator where = new QueryTranslator();
            string conditionString = where.Translate(conditionExpression);
            string orderString = string.Empty;
            if (orderExpression != null)
                orderString = where.Translate(orderExpression);
            if (isFilterNull == true)
                conditionString = conditionString.SqlFilterNull();

            return GetTopData(top,conditionString, orderString, orderMethod, flag,isFilterMerchant);
        }

        /// <summary>
        /// 获取Top，根据查询条件及排序字段、排序方法
        /// </summary>
        /// <param name="top"></param>
        /// <param name="conditionString">查询条件字符串，SQL语句中的WHERE表达式</param>
        /// <param name="orderString">排序字段字符串，SQL语句中的OrderBy表达式，字段间用“,”号隔开</param>
        /// <param name="orderMethod">排序方法，升序或降序排列</param>
        /// <returns>返回满足条件的第一条记录，记录不存在则返回Null</returns>
        public List<T_BAS_RecieverAddress> GetTopData(string top,string conditionString = "", string orderString = "", OrderMethods orderMethod = OrderMethods.Default, LockType flag = LockType.Default, bool isFilterMerchant = true)
        {
            if (string.IsNullOrEmpty(top) == true)
            {
                throw new Exception("top不能为空,例:top=6或top=10%");
            }
            if (top.Contains("%"))
            {
                top = string.Format(" top {0} percent ", top.Replace("%",string.Empty));
            }
            else
            {
                top = string.Format(" top {0} ", top);
            }

            if (conditionString == null)
                conditionString = string.Empty;
            if (orderString == null)
                orderString = string.Empty;
            SqlParameter[] parameters = {
								            new SqlParameter("@top", SqlDbType.NVarChar), 
								            new SqlParameter("@strCondition", SqlDbType.NVarChar), 
								            new SqlParameter("@strOrder", SqlDbType.NVarChar),
                                            new SqlParameter("@strLockType", SqlDbType.NVarChar),
                                            new SqlParameter("@SMerchantGuid", SqlDbType.UniqueIdentifier),
                                            new SqlParameter("@isFilterMerchant", SqlDbType.Bit),
                                        };
            parameters[0].Value = top.Trim();
            parameters[1].Value = conditionString.Trim();
            parameters[2].Value = orderString.Trim();
            parameters[3].Value = flag.ToSqlLock();
            parameters[4].Value = CurrentManage.SMerchantGuid;
            if (orderString.Trim() != string.Empty)
                parameters[2].Value += orderMethod == OrderMethods.DESC ? " DESC" : " ASC";
            parameters[5].Value = isFilterMerchant;

             List<T_BAS_RecieverAddress> dataList = new List<T_BAS_RecieverAddress>();
			           
            SqlDataReader dataReader = SqlHelper.ExecuteReader("PT_BAS_RecieverAddress_GetTopData",CommandType.StoredProcedure, parameters, sqlRTransaction);

			try
            {
                while (dataReader.Read())
                {
                    dataList.Add(LoadModel(dataReader));
                }
            }
            catch (Exception ex)
            {
                dataReader.Close();
                Dispose();
                throw new Exception(string.Format("GetTopData获取数据出错,conditionString={0},异常:{1}", conditionString, ex.Message), ex);
            }
            dataReader.Close();
    						
            return dataList;             
        }

        #endregion
		
        #region GetFirstData
        
		/// <summary>
        /// 获取第一条记录，根据查询条件Lambda表达式及排序字段Lambda表达式、排序方法
        /// </summary>
        /// <param name="conditionExpression">查询条件Lambda表达式</param>
        /// <param name="orderString">排序字段Lambda表达式，字段间用“+”号连接</param>
        /// <param name="orderMethod">排序方法，升序或降序排列</param>
        /// <returns>返回满足条件的记录集</returns>
        public T_BAS_RecieverAddress GetFirstData(Expression<Func<T_BAS_RecieverAddress, bool>> conditionExpression, bool isFilterNull = false, Expression<Func<T_BAS_RecieverAddress, object>> orderExpression = null, OrderMethods orderMethod = OrderMethods.Default,LockType flag=LockType.Default, bool isFilterMerchant = true)
        {
            QueryTranslator where = new QueryTranslator();
            string conditionString = where.Translate(conditionExpression);
            string orderString = string.Empty;
            if (orderExpression != null)
                orderString = where.Translate(orderExpression);
            if (isFilterNull == true)
                conditionString = conditionString.SqlFilterNull();
            
            return GetFirstData(conditionString, orderString, orderMethod, flag,isFilterMerchant);        
        }

        /// <summary>
        /// 获取第一条记录，根据查询条件及排序字段、排序方法
        /// </summary>
        /// <param name="conditionString">查询条件字符串，SQL语句中的WHERE表达式</param>
        /// <param name="orderString">排序字段字符串，SQL语句中的OrderBy表达式，字段间用“,”号隔开</param>
        /// <param name="orderMethod">排序方法，升序或降序排列</param>
        /// <returns>返回满足条件的第一条记录，记录不存在则返回Null</returns>
        public T_BAS_RecieverAddress GetFirstData(string conditionString = "", string orderString = "", OrderMethods orderMethod = OrderMethods.Default,LockType flag=LockType.Default, bool isFilterMerchant = true)
        { 
            if (conditionString == null)
                conditionString = string.Empty;
            if (orderString == null)
                orderString = string.Empty;
            SqlParameter[] parameters = {
								            new SqlParameter("@strCondition", SqlDbType.NVarChar), 
								            new SqlParameter("@strOrder", SqlDbType.NVarChar),
                                            new SqlParameter("@strLockType", SqlDbType.NVarChar),
                                            new SqlParameter("@SMerchantGuid", SqlDbType.UniqueIdentifier),
                                            new SqlParameter("@isFilterMerchant", SqlDbType.Bit),
                                        };
            parameters[0].Value = conditionString.Trim();
            parameters[1].Value = orderString.Trim();
            parameters[2].Value = flag.ToSqlLock();
            parameters[3].Value = CurrentManage.SMerchantGuid;
            if (orderString.Trim() != string.Empty)
                parameters[1].Value += orderMethod == OrderMethods.DESC ? " DESC" : " ASC";
            parameters[4].Value = isFilterMerchant;
                
            SqlDataReader dataReader = SqlHelper.ExecuteReader("PT_BAS_RecieverAddress_GetFirstData", CommandType.StoredProcedure, parameters, sqlRTransaction);

            T_BAS_RecieverAddress data = null;
            try
            {
                if (dataReader.Read())
                    data = LoadModel(dataReader);
            }
            catch (Exception ex)
            {
                dataReader.Close();
                Dispose();
                throw new Exception(string.Format("GetFirstData()参数:conditionString={0}获取数据出错,异常:{1}", conditionString, ex.Message), ex);
            }         
            dataReader.Close();
            
            return data;
        }
        #endregion

        #region Update
        /// 更新一条记录
        /// </summary>
        /// <param name="valueExpression">待更新的记录</param>
        /// <param name="conditionExpression">要更新的条件</param>
        /// <returns>返回更新结果，成功为True，失败为False</returns>        
        public void Update(Expression<Func<T_BAS_RecieverAddress, object[]>> valueExpression, Expression<Func<T_BAS_RecieverAddress, bool>> conditionExpression, bool isFilterMerchant = true)
        {            
            QueryTranslator query = new QueryTranslator();
            string value = query.Translate(valueExpression).Replace(")(", ",").Substring(1);
            value = value.Substring(0, value.Length - 1);
            string condition = query.Translate(conditionExpression);
            if (condition == string.Empty)
                throw new Exception("删除条件不能为null或空");


            SqlParameter[] parameters = {
                                            new SqlParameter("@value", SqlDbType.NVarChar),
                                            new SqlParameter("@strCondition", SqlDbType.NVarChar),
                                            new SqlParameter("@SMerchantGuid", SqlDbType.UniqueIdentifier),
                                            new SqlParameter("@isFilterMerchant", SqlDbType.Bit),
										};

            parameters[0].Value = value;
            parameters[1].Value = condition;
			parameters[2].Value = CurrentManage.SMerchantGuid;
            parameters[3].Value = isFilterMerchant;
            try
            {
                int rowsAffected = SqlHelper.ExecuteNonQuery("PT_BAS_RecieverAddress_SingleUpdate", CommandType.StoredProcedure, parameters, sqlRTransaction);
                bool result = rowsAffected != -1 ? true : false;

                if (result == false)
                    throw new Exception("更新数据失败");
            }
            catch (Exception ex)
            {
                Dispose();
                throw new Exception(string.Format("Update()参数:conditionString={0}更新数据失败,异常:{1}", condition, ex.Message), ex);
            }
        }
        /// <summary>
        /// 更新一条记录
        /// </summary>
        /// <param name="data">待更新的记录</param>
        /// <returns>返回更新结果，成功为True，失败为False</returns>
        public void Update(T_BAS_RecieverAddress data, bool isFilterMerchant = true)
        {
            SqlParameter[] parameters = {
                                            new SqlParameter("@SUpdateDate", SqlDbType.DateTime),
                                            new SqlParameter("@SUpdateUserName", SqlDbType.NVarChar),
                                            new SqlParameter("@SMerchantGuid", SqlDbType.UniqueIdentifier),
                                            new SqlParameter("@isFilterMerchant", SqlDbType.Bit),
											new SqlParameter("@RecieverAddressGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@MemberGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@Reciever", SqlDbType.NVarChar),
											new SqlParameter("@Province", SqlDbType.NVarChar),
											new SqlParameter("@City", SqlDbType.NVarChar),
											new SqlParameter("@Area", SqlDbType.NVarChar),
											new SqlParameter("@Address", SqlDbType.NVarChar),
											new SqlParameter("@Telephone", SqlDbType.NVarChar),
											new SqlParameter("@Zip", SqlDbType.NVarChar),
											new SqlParameter("@IsDefualt", SqlDbType.Bit),
										};										
			
            parameters[0].Direction = ParameterDirection.Output;
            parameters[1].Value = CurrentManage.UserName;
            parameters[2].Value = data.SMerchantGuid==null ? CurrentManage.SMerchantGuid : data.SMerchantGuid;
            parameters[3].Value = isFilterMerchant;
			parameters[4].Value = data.RecieverAddressGuid;
			parameters[5].Value = data.MemberGuid;
			parameters[6].Value = data.Reciever;
			parameters[7].Value = data.Province;
			parameters[8].Value = data.City;
			parameters[9].Value = data.Area;
			parameters[10].Value = data.Address;
			parameters[11].Value = data.Telephone;
			parameters[12].Value = data.Zip;
			parameters[13].Value = data.IsDefualt;
			try
            {
                int rowsAffected = SqlHelper.ExecuteNonQuery("PT_BAS_RecieverAddress_Update", CommandType.StoredProcedure, parameters, sqlRTransaction);
                bool result = rowsAffected != -1 ? true : false;
                
                if (result == false)
                    throw new Exception("更新数据失败");
            }
            catch (Exception ex)
            {
                Dispose();
                throw new Exception(string.Format("Update()参数:conditionString={0}更新数据失败,异常:{1}", data.ToString(), ex.Message), ex);
            }
        }
        
        /// <summary>
        /// 批量更新记录集，根据dataList中各个记录的状态
        /// 记录的状态为ToBeAdd的，新增这条记录到数据库
        /// 记录的状态为ToBeDelete的，删除这条记录到数据库
        /// 记录的状态为ToBeUpdate的，更新这条记录到数据库
        /// 记录的状态为Original的，不对这条记录进行任何操作
        /// </summary>
        /// <param name="dataList">待更新的记录集</param>
        /// <returns>返回更新结果，成功为True，失败为False</returns>        
        public void UpdateList(List<T_BAS_RecieverAddress> dataList)
        {
            bool istran = false;
            if (sqlRTransaction.IsTransaction == false)
            {
                istran = true;
                sqlRTransaction.BeginTransaction();
            }

            DataTable dataListAdd = SqlHelper.GetTables("T_BAS_RecieverAddress",sqlRTransaction);

            List<T_BAS_RecieverAddress> dataListUpdate = new List<T_BAS_RecieverAddress>();
            List<string> dataListDelete = new List<string>();            
            StringBuilder sbDelete = new StringBuilder();
            sbDelete.Append(" RecieverAddressGuid in (");
            int deleteCount = 0;
            string strSql = string.Empty;
            foreach (var data in dataList)
            {
                switch (data.EntityState)
                {
                    case EntityStates.ToBeAdd:
                        DataRow dr = dataListAdd.NewRow();
            			dr["RecieverAddressGuid"] = data.RecieverAddressGuid;
            			dr["MemberGuid"] = data.MemberGuid;
            			dr["Reciever"] = data.Reciever;
            			dr["Province"] = data.Province;
            			dr["City"] = data.City;
            			dr["Area"] = data.Area;
            			dr["Address"] = data.Address;
            			dr["Telephone"] = data.Telephone;
            			dr["Zip"] = data.Zip;
            			dr["IsDefualt"] = data.IsDefualt;
                        dr["SCreateDate"] = DateTime.Now;
                        dr["SCreateUserName"] = CurrentManage.UserName;
                        dr["SMerchantGuid"] = CurrentManage.SMerchantGuid;
                        dataListAdd.Rows.Add(dr);
                        break;
                    case EntityStates.ToBeDelete:
                        sbDelete.AppendFormat(" '{0}',", data.RecieverAddressGuid);
                        deleteCount++;
                        if (deleteCount == 20)
                        {
                            sbDelete.Append(")");
                            deleteCount = 0;
                            strSql = sbDelete.ToString();
                            dataListDelete.Add(strSql.Replace(",)",") "));
                            sbDelete.Clear();
                            sbDelete.Append(" RecieverAddressGuid in (");
                        }
                        break;
                    case EntityStates.ToBeUpdated:
                        dataListUpdate.Add(data);
                        break;
                }
            }
            if (sbDelete.Length>0 && sbDelete.ToString() != " RecieverAddressGuid in (")
            {
                sbDelete.Append(")");
                strSql = sbDelete.ToString();
                dataListDelete.Add(strSql.Replace(",)",") "));
                sbDelete.Clear();
            }

            #region 更新到数据库
            if (dataListAdd.Rows.Count>0)
            { 
            //添加
            SqlHelper.BatchAddData(new DataTable[] { dataListAdd }, sqlRTransaction);
            }
            //修改
            foreach(var v in dataListUpdate)
            {
                Update(v);
            }
            //删除
            foreach(var v in dataListDelete)
            {
                Delete(v);
            }
            #endregion

            if (istran == true)
                sqlRTransaction.Commit();

            dataListAdd.Clear();
            dataListUpdate.Clear();
            dataListDelete.Clear();
            dataList.ForEach(a => a.EntityState = EntityStates.Original);
        }

        #endregion
         
        #region Delete
        /// <summary>
        /// 删除一条记录，根据记录的GUID值
        /// </summary>
        /// <param name="dataGuid">待删除的记录的GUID值</param>
        /// <returns>返回删除结果，成功为True，失败为False</returns>
        public void Delete(Guid dataGuid, bool isFilterMerchant = true)
        { 
			Delete(string.Format("RecieverAddressGuid = '{0}'",dataGuid),isFilterMerchant);
        }
                
         /// <summary>
        /// 根据条件删除记录
        /// </summary>
        /// <param name="dataGuid">删除条件</param>
        /// <returns>返回删除结果，成功为True，失败为False</returns>
        public void Delete(Expression<Func<T_BAS_RecieverAddress, bool>> conditionExpression, bool isFilterMerchant = true)
        { 
            QueryTranslator where = new QueryTranslator();
            string conditionString = where.Translate(conditionExpression);
            Delete(conditionString,isFilterMerchant);
        }
        
        /// <summary>
        /// 批量删除数据
        /// 记录的状态为ToBeAdd的，新增这条记录到数据库
        /// 记录的状态为ToBeDelete的，删除这条记录到数据库
        /// 记录的状态为ToBeUpdate的，更新这条记录到数据库
        /// 记录的状态为Original的，不对这条记录进行任何操作
        /// </summary>
        /// <param name="dataList">待更新的记录集</param>
        /// <returns>返回更新结果，成功为True，失败为False</returns>        
        public void DeleteList(List<T_BAS_RecieverAddress> dataList, bool isFilterMerchant = true)
        {
            bool istran = false;
            if (sqlRTransaction.IsTransaction == false)
            {
                istran = true;
                sqlRTransaction.BeginTransaction();
            }
            List<string> dataListDelete = new List<string>();            
            StringBuilder sbDelete = new StringBuilder();
            sbDelete.Append(" RecieverAddressGuid in (");
            int deleteCount = 0;
            string strSql = string.Empty;
            foreach (var data in dataList)
            {              
                sbDelete.AppendFormat(" '{0}',", data.RecieverAddressGuid);
                deleteCount++;
                if (deleteCount == 20)
                {
                    sbDelete.Append(")");
                    deleteCount = 0;
                    strSql = sbDelete.ToString();
                    dataListDelete.Add(strSql.Replace(",)",") "));
                    sbDelete.Clear();
                    sbDelete.Append(" RecieverAddressGuid in (");
                }
            }
            if (sbDelete.Length>0 && sbDelete.ToString() != " RecieverAddressGuid in (")
            {
                sbDelete.Append(")");
                strSql = sbDelete.ToString();
                dataListDelete.Add(strSql.Replace(",)",") "));
                sbDelete.Clear();
            }

            #region 更新到数据库           
            //删除
            foreach(var v in dataListDelete)
            {
                Delete(v,isFilterMerchant);
            }
            #endregion

            if (istran == true)
                sqlRTransaction.Commit();

            dataListDelete.Clear();
        }
        
         /// <summary>
        /// 根据条件删除记录
        /// </summary>
        /// <param name="dataGuid">删除条件</param>
        /// <returns>返回删除结果，成功为True，失败为False</returns>
        public void Delete(string conditionString = "", bool isFilterMerchant = true)
        {
            if (conditionString == null || conditionString ==String.Empty)
                throw new Exception("删除条件不能为null或空");
            SqlParameter[] parameters =
            {
                new SqlParameter("@strCondition", SqlDbType.NVarChar),
                new SqlParameter("@SMerchantGuid", SqlDbType.UniqueIdentifier),
                new SqlParameter("@isFilterMerchant", SqlDbType.Bit),
            };
            parameters[0].Value = conditionString; 
            parameters[1].Value = CurrentManage.SMerchantGuid;
            parameters[2].Value = isFilterMerchant;
            try
            {
                int rowsAffected = SqlHelper.ExecuteNonQuery("PT_BAS_RecieverAddress_Delete", CommandType.StoredProcedure, parameters, sqlRTransaction);
                
                if(rowsAffected == -1)
                    throw new Exception("删除数据失败");
            }
            catch (Exception ex)
            {
                Dispose();
                throw new Exception(string.Format("Delete()参数:conditionString={0}删除数据失败,异常:{1}", conditionString, ex.Message), ex);
            }
        }
        
        #endregion
        
        #region GetList
         
		/// <summary>
        /// 获取记录集，根据查询条件Lambda表达式及排序字段Lambda表达式、排序方法
        /// </summary>
        /// <param name="conditionExpression">查询条件Lambda表达式</param>
        /// <param name="orderString">排序字段Lambda表达式，字段间用“+”号连接</param>
        /// <param name="orderMethod">排序方法，升序或降序排列</param>
        /// <returns>返回满足条件的记录集</returns>
        public List<T_BAS_RecieverAddress> GetList(Expression<Func<T_BAS_RecieverAddress, bool>> conditionExpression, bool isFilterNull = false, Expression<Func<T_BAS_RecieverAddress, object>> orderExpression = null, OrderMethods orderMethod = OrderMethods.Default,LockType flag=LockType.Default, bool isFilterMerchant = true)
        {
            QueryTranslator where = new QueryTranslator();
            string conditionString = where.Translate(conditionExpression);
            string orderString = string.Empty;
            if (orderExpression != null)
                orderString = where.Translate(orderExpression);
            if (isFilterNull == true)
                conditionString = conditionString.SqlFilterNull();
            
            return GetList(conditionString, orderString, orderMethod, flag,isFilterMerchant);
         }
        
        /// <summary>
        /// 获取记录集，根据查询条件及排序字段、排序方法
        /// </summary>
        /// <param name="conditionString">查询条件字符串，SQL语句中的WHERE表达式</param>
        /// <param name="orderString">排序字段字符串，SQL语句中的OrderBy表达式，字段间用“,”号隔开</param>
        /// <param name="orderMethod">排序方法，升序或降序排列</param>
        /// <returns>返回满足条件的记录集</returns>
        public List<T_BAS_RecieverAddress> GetList(string conditionString = "", string orderString = "", OrderMethods orderMethod = OrderMethods.Default,LockType flag=LockType.Default, bool isFilterMerchant = true)
        { 
            if (conditionString == null)
                conditionString = string.Empty;
            if (orderString == null)
                orderString = string.Empty;
			SqlParameter[] parameters = {
											new SqlParameter("@strCondition", SqlDbType.NVarChar), 
											new SqlParameter("@strOrder", SqlDbType.NVarChar),
                                            new SqlParameter("@strLockType", SqlDbType.NVarChar),
                                            new SqlParameter("@SMerchantGuid", SqlDbType.UniqueIdentifier),
                                            new SqlParameter("@isFilterMerchant", SqlDbType.Bit),
										};
            parameters[0].Value = conditionString.Trim();
            parameters[1].Value = orderString.Trim();
            parameters[2].Value = flag.ToSqlLock();
            parameters[3].Value = CurrentManage.SMerchantGuid;
            parameters[4].Value = isFilterMerchant;
			if (orderString.Trim() != string.Empty)
				parameters[1].Value += orderMethod == OrderMethods.DESC ? " DESC" : " ASC";
			
            List<T_BAS_RecieverAddress> dataList = new List<T_BAS_RecieverAddress>();
			           
            SqlDataReader dataReader = SqlHelper.ExecuteReader("PT_BAS_RecieverAddress_GetList",CommandType.StoredProcedure, parameters, sqlRTransaction);

			try
            {
                while (dataReader.Read())
                {
                    dataList.Add(LoadModel(dataReader));
                }
            }
            catch (Exception ex)
            {
                dataReader.Close();
                Dispose();
                throw new Exception(string.Format("GetList获取数据出错,conditionString={0},异常:{1}", conditionString, ex.Message), ex);
            }
            dataReader.Close();
    						
            return dataList;             
        }	
        
        #endregion
        
        #region GetCount
		
		/// <summary>
        /// 获取记录数，根据查询条件Lambda表达式
        /// </summary>
        /// <param name="conditionExpression">查询条件Lambda表达式</param>
        /// <returns>返回满足条件的记录集</returns>
        public int GetCount(Expression<Func<T_BAS_RecieverAddress, bool>> conditionExpression, bool isFilterNull = false, bool isFilterMerchant = true)
        {
            QueryTranslator where = new QueryTranslator();
            string conditionString = where.Translate(conditionExpression);
            if (isFilterNull == true)
                conditionString = conditionString.SqlFilterNull();
            return GetCount(conditionString,isFilterMerchant);
        }

        /// <summary>
        /// 获取记录数，根据查询条件
        /// </summary>
        /// <param name="conditionString">查询条件字符串，SQL语句中的WHERE表达式</param>
        /// <returns>返回满足条件的记录数</returns>
        public int GetCount(string conditionString = "", bool isFilterMerchant = true)
        { 
            if (conditionString == null)
                conditionString = string.Empty; 
            SqlParameter[] parameters = {
											new SqlParameter("@strCondition", SqlDbType.NVarChar),
                                            new SqlParameter("@iRecordCount", SqlDbType.Int),
                                            new SqlParameter("@SMerchantGuid", SqlDbType.UniqueIdentifier),
                                            new SqlParameter("@isFilterMerchant", SqlDbType.Bit),
										};
            parameters[0].Value = conditionString.Trim();
            parameters[1].Direction = ParameterDirection.Output;
            parameters[2].Value = CurrentManage.SMerchantGuid;
            parameters[3].Value = isFilterMerchant;
            int recordCount;
            SqlDataReader dataReader =  SqlHelper.ExecuteReader("PT_BAS_RecieverAddress_GetCount", CommandType.StoredProcedure, parameters, sqlRTransaction);
            try
            {
                recordCount = (int)parameters[1].Value;
            }
            catch (Exception ex)
            {
                dataReader.Close();
                Dispose();
                throw new Exception(string.Format("GetCount获取总记录出错,conditionString={0},异常:{1}", conditionString, ex.Message), ex);
            }
            dataReader.Close();
            
            return recordCount;
        } 
        
        #endregion
        
        #region GetPageList
		
		/// <summary>
        /// 获取记录集，根据查询条件Lambda表达式及排序字段Lambda表达式、排序方法
        /// </summary>
        /// <param name="page">页号</param>
        /// <param name="pageSize">每页的记录数</param>
        /// <param name="pageCount">返回总页数</param>
        /// <param name="recordCount">返回总记录数</param>
        /// <param name="conditionExpression">查询条件Lambda表达式</param>
        /// <param name="orderString">排序字段Lambda表达式，字段间用“+”号连接</param>
        /// <param name="orderMethod">排序方法，升序或降序排列</param>
        /// <returns>返回满足条件的记录集</returns>
        public List<T_BAS_RecieverAddress> GetPageList(int page, int pageSize, out int pageCount, out int recordCount, Expression<Func<T_BAS_RecieverAddress, bool>> conditionExpression, bool isFilterNull = false, Expression<Func<T_BAS_RecieverAddress, object>> orderExpression = null, OrderMethods orderMethod = OrderMethods.Default,LockType flag=LockType.Default, bool isFilterMerchant = true)
        {
            QueryTranslator where = new QueryTranslator();
            string conditionString = where.Translate(conditionExpression);
            string orderString = string.Empty;
            if (orderExpression != null)
                orderString = where.Translate(orderExpression);
            if (isFilterNull == true)
                conditionString = conditionString.SqlFilterNull();
           
            return GetPageList(page, pageSize,out pageCount, out recordCount, conditionString, orderString, orderMethod, flag,isFilterMerchant);
        }
        /// <summary>
        /// 获取记录集，根据查询条件Lambda表达式及排序字段Lambda表达式、排序方法
        /// </summary>
        /// <param name="gridModel">查询条件</param>
        /// <param name="conditionExpression">查询条件Lambda表达式</param>
        /// <param name="orderString">排序字段Lambda表达式，字段间用“+”号连接</param>
        /// <param name="orderMethod">排序方法，升序或降序排列</param>
        /// <returns>返回满足条件的记录集</returns>
        public List<T_BAS_RecieverAddress> GetPageList(GridModel gridModel, Expression<Func<T_BAS_RecieverAddress, bool>> conditionExpression, bool isFilterNull = false, Expression<Func<T_BAS_RecieverAddress, object>> orderExpression = null, OrderMethods orderMethod = OrderMethods.Default, LockType flag = LockType.Default, bool isFilterMerchant = true)
        {
            return GetPageList(gridModel.page, gridModel.rows, out gridModel.pageCount, out gridModel.recordCount, conditionExpression,isFilterNull, orderExpression, orderMethod, flag,isFilterMerchant);
        }
        /// <summary>
        /// 获取记录集，根据查询条件及排序字段、排序方法，分页
        /// </summary>      
        /// <param name="page">页号</param>
        /// <param name="pageSize">每页的记录数</param>
        /// <param name="pageCount">返回总页数</param>
        /// <param name="recordCount">返回总记录数</param>
        /// <param name="conditionString">查询条件字符串，SQL语句中的WHERE表达式</param>
        /// <param name="orderString">排序字段字符串，SQL语句中的OrderBy表达式，字段间用“,”号隔开</param>
        /// <param name="orderMethod">排序方法，升序或降序排列</param>
        /// <returns>返回满足条件的记录集，分页</returns>
        public List<T_BAS_RecieverAddress> GetPageList(int page, int pageSize, out int pageCount, out int recordCount, string conditionString = "", string orderString = "", OrderMethods orderMethod = OrderMethods.Default,LockType flag=LockType.Default, bool isFilterMerchant = true)
        { 
            if (conditionString == null)
                conditionString = string.Empty;
            if (orderString == null)
                orderString = string.Empty;
            List<T_BAS_RecieverAddress> dataList = new List<T_BAS_RecieverAddress>();
            SqlParameter[] parameters = {
											new SqlParameter("@iPage", SqlDbType.Int),
											new SqlParameter("@iPageSize", SqlDbType.Int),
											new SqlParameter("@iPageCount", SqlDbType.Int),
											new SqlParameter("@iRecordCount", SqlDbType.Int),
											new SqlParameter("@strCondition", SqlDbType.NVarChar),
										    new SqlParameter("@strOrder", SqlDbType.NVarChar),
                                            new SqlParameter("@strLockType", SqlDbType.NVarChar),
                                            new SqlParameter("@SMerchantGuid", SqlDbType.UniqueIdentifier),
                                            new SqlParameter("@isFilterMerchant", SqlDbType.Bit),
                                        };
            parameters[0].Value = page;
            parameters[1].Value = pageSize;
            parameters[2].Direction = ParameterDirection.Output;
            parameters[3].Direction = ParameterDirection.Output;
            parameters[4].Value = conditionString.Trim();
            parameters[5].Value = orderString.Trim();
            parameters[6].Value = flag.ToSqlLock();
            parameters[7].Value = CurrentManage.SMerchantGuid;
            parameters[8].Value = isFilterMerchant;
			if (orderString.Trim() != string.Empty)
				parameters[5].Value += orderMethod == OrderMethods.DESC ? " DESC" : " ASC";			
			
			SqlDataReader dataReader = SqlHelper.ExecuteReader("PT_BAS_RecieverAddress_GetPageList",CommandType.StoredProcedure, parameters,sqlRTransaction);
            try
            {
                while (dataReader.Read())
                {
                    dataList.Add(LoadModel(dataReader));
                }
			}
            catch (Exception ex)
            {
                dataReader.Close();
                Dispose();
                throw new Exception(string.Format("GetPageList获取数据记录出错,conditionString={0},异常:{1}", conditionString, ex.Message), ex);
            }
            dataReader.Close();
			
            pageCount = (int)parameters[2].Value;
            recordCount = (int)parameters[3].Value;
			
            return dataList;
        }
        
        #endregion
   
        /// <summary>
        /// 获取记录实体，从 DataReader 的当前记录装载
        /// </summary>
        /// <param name="dataReader">DataReader 对象</param>
        /// <returns>返回 DataReader 里下一条记录，记录不存在则返回Null</returns>
        private T_BAS_RecieverAddress LoadModel(SqlDataReader dataReader)
        {
            T_BAS_RecieverAddress data = new T_BAS_RecieverAddress();
			if (dataReader["RecieverAddressGuid"] != DBNull.Value)
				data.RecieverAddressGuid = (Guid)dataReader["RecieverAddressGuid"];
			if (dataReader["MemberGuid"] != DBNull.Value)
				data.MemberGuid = (Guid)dataReader["MemberGuid"];
			if (dataReader["Reciever"] != DBNull.Value)
				data.Reciever = (string)dataReader["Reciever"];
			if (dataReader["Province"] != DBNull.Value)
				data.Province = (string)dataReader["Province"];
			if (dataReader["City"] != DBNull.Value)
				data.City = (string)dataReader["City"];
			if (dataReader["Area"] != DBNull.Value)
				data.Area = (string)dataReader["Area"];
			if (dataReader["Address"] != DBNull.Value)
				data.Address = (string)dataReader["Address"];
			if (dataReader["Telephone"] != DBNull.Value)
				data.Telephone = (string)dataReader["Telephone"];
			if (dataReader["Zip"] != DBNull.Value)
				data.Zip = (string)dataReader["Zip"];
			if (dataReader["IsDefualt"] != DBNull.Value)
				data.IsDefualt = (bool)dataReader["IsDefualt"];
			if (dataReader["SMerchantGuid"] != DBNull.Value)
				data.SMerchantGuid = (Guid)dataReader["SMerchantGuid"];
            data.EntityState = EntityStates.Original; 
            return data;
        }
        
          #region IDisposable 成员
        /// <summary>
        /// 回收
        /// </summary>
        public void Dispose()
        {
            sqlRTransaction.Dispose();
        }

        #endregion

    }
}

