//==============================================================
//  版权所有：深圳杰文科技
//  文件名：SqlServerDao.cs
//  版本：V1.0  
//  创建者：Jay  ( QQ： 85363208 )
//  创建时间：2018-3-3 23:16
//  创建描述：
//  修改者：
//  修改时间：
//  修改说明： 
//==============================================================

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using Infrastructure.Utilities;

namespace Infrastructure.DAO
{
	//有连接池，自动管理事务。
	public class SqlDao
	{
		private SqlConnection conn = null;
		private SqlTransaction trans = null;

		public SqlDao(string connectionString)
		{
			conn = new SqlConnection(connectionString);
			conn.Open();
		}

		public string ConnectionString
		{
			get;
			private set;
		}

		public bool BeginTransaction()
		{
			trans = conn.BeginTransaction();
			return true;
		}

		public bool CommitTransaction(string connectionString)
		{
			try
			{
				trans.Commit();
				return true;
			}
			catch
			{
				throw;
			}
			finally
			{
				trans.Dispose();
			}
		}

		public bool RollbackTransaction(string connectionString)
		{
			try
			{
				trans.Rollback();
				return true;
			}
			catch
			{
				throw;
			}
			finally
			{
				trans.Dispose();
			}
		}

		public List<T> Select<T>(string sql, params string[] args) where T : new()
		{
			Type type = typeof(T);

			sql = sql.Fmt(args);
			DbUtil.Log(sql);

			List<T> list = null;
			using (SqlDataAdapter da = new SqlDataAdapter(sql, conn))
			{
				using (DataTable table = new DataTable())
				{
					da.Fill(table);
					list = DataTableHelper.Mapping<T>(table);
				}
			}
			return list;
		}

		public T FirstOrDefault<T>(string sql, params string[] args) where T : new()
		{
			Type type = typeof(T);

			sql = sql.Fmt(args);
			DbUtil.Log(sql);

			using (SqlDataAdapter da = new SqlDataAdapter(sql, conn))
			{
				using (DataTable table = new DataTable())
				{
					da.Fill(table);
					if (table.Rows.Count == 0)
					{
						return default(T);
					}
					else
					{
						T obj = table.Rows[0].To<T>();
						return obj;
					}
				}
			}
		}

		public void Dispose()
		{
			if (trans != null)
			{
				trans.Dispose();
			}

			if (conn != null)
			{
				conn.Dispose();
			}
		}
	}
}
