使用基本的Dapper,好用的轻量级Orm框架
Posted 岁月如歌_E
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用基本的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 [email protected]";
var data = DBHelper<Member>.Query(query, new { id=id});
this.Response.Write((object)data);
this.Response.End();
}
上方的Member为实体对象,如果只需要实体对象Member部分字段,可选择性创建
自己记录下省的以后到处找。。
以上是关于使用基本的Dapper,好用的轻量级Orm框架的主要内容,如果未能解决你的问题,请参考以下文章