使用基本的Dapper,好用的輕量級Orm框架
public class DBHelper<T>where T:class
{
/// <summary>
/// 數據庫連接字符串
/// </summary>
public static readonly string connectionString = ConfigurationManager.ConnectionStrings["ConString_String"].ConnectionString;
#region Search
/// <summary>
/// 查詢列表
/// </summary>
/// <param name="sql">查詢的sql</param>
/// <param name="param">替換參數</param>
/// <returns></returns>
public static List<T> Query(string sql, object param)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
return con.Query<T>(sql, param).ToList();
}
}
/// <summary>
/// 查詢第一個數據
/// </summary>
/// <param name="sql"></param>
/// <param name="param"></param>
/// <returns></returns>
public static T QueryFirst(string sql, object param)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
return con.QueryFirst<T>(sql, param);
}
}
/// <summary>
/// 查詢第一個數據沒有返回默認值
/// </summary>
/// <param name="sql"></param>
/// <param name="param"></param>
/// <returns></returns>
public static T QueryFirstOrDefault(string sql, object param)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
return con.QueryFirstOrDefault<T>(sql, param);
}
}
/// <summary>
/// 查詢單條數據
/// </summary>
/// <param name="sql"></param>
/// <param name="param"></param>
/// <returns></returns>
public static T QuerySingle(string sql, object param)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
return con.QuerySingle<T>(sql, param);
}
}
/// <summary>
/// 查詢單條數據沒有返回默認值
/// </summary>
/// <param name="sql"></param>
/// <param name="param"></param>
/// <returns></returns>
public static T QuerySingleOrDefault(string sql, object param)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
return con.QuerySingleOrDefault<T>(sql, param);
}
}
#endregion
#region Update、Create、Delete
/// <summary>
/// 增刪改
/// </summary>
/// <param name="sql"></param>
/// <param name="param"></param>
/// <returns></returns>
public static int Execute(string sql, object param)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
return con.Execute(sql, param);
}
}
#endregion
#region Storage
/// <summary>
/// 帶參數的存儲過程
/// </summary>
/// <param name="sql"></param>
/// <param name="param"></param>
/// <returns></returns>
public static List<T> ExecutePro(string proc, object param)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
List<T> list = con.Query<T>(proc,
param,
null,
true,
null,
CommandType.StoredProcedure).ToList();
return list;
}
}
#endregion
}
使用dapper的nuget包目前最低支持.net fromwork4.51,所以個人感覺比ADO,要輕松一點,也很容易學習。
public void Search()
{
var id = 1;
string query = "select * from member where id=@id";
var data = DBHelper<Member>.Query(query, new { id=id});
this.Response.Write((object)data);
this.Response.End();
}
上方的Member為實體對象,如果只需要實體對象Member部分字段,可選擇性創建
自己記錄下省的以後到處找。。
使用基本的Dapper,好用的輕量級Orm框架