.net core 3.1 Dapper性能王者的ORM框架
什么是dapper?
官网地址:https://dapper-tutorial.net/
Dapper 是一个简单的 .NET 对象映射器,在速度方面拥有Micro ORM之王的称号,几乎与使用原始 ADO.NET 数据读取器一样快。ORM 是一个对象关系映射器,负责数据库和编程语言之间的映射。
Dapper 通过提供有用的扩展方法来查询数据库来扩展 IDbConnection。
直接上代码案列
首先环境是.net core 3.1
在nuget程序包中呢,搜索集
dapper,
dapper.extension
dapper.contrib
注意要是.net core版本**
IDbConnection 作为dapper重要的接口 作为连接数据库专用
public class ConnectionOption
{
private static IDbConnection _dbConnection = new SqlConnection();
public static IDbConnection DbConnection
{
get
{
_dbConnection.ConnectionString = "server=DESKTOP -23DM9NS;database=ZHIBO;userid=tudawei;password=123456";
return _dbConnection;
}
}
}
对于dapper原有的方法进行简单的封装,加以处理,关于事务,参数等操作,这里只是列举了两个查询操作,更多的增删改查以及存储过程可以自己去看文档。
public class DapperHelper
{
//}
/// <summary>
/// 单个查询
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sql">sql语句</param>
/// <param name="param">参数</param>
/// <param name="transaction">事务</param>
/// <param name="commandTimeout">超时时间</param>
/// <param name="commandType">command类型</param>
/// <returns></returns>
public T QueryFirst<T>(string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) {
ConnectionOption.DbConnection.Open();
using (transaction = ConnectionOption.DbConnection.BeginTransaction())
{
var user = ConnectionOption.DbConnection.QueryFirstOrDefault<T>(sql, param, transaction, commandTimeout, commandType);
transaction.Commit();
ConnectionOption.DbConnection.Close();
return user;
}
}
/// <summary>
/// 多个查询
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sql">sql语句</param>
/// <param name="param">参数</param>
/// <param name="transaction">事务</param>
/// <param name="buffered">缓冲/缓存</param>
/// <param name="commandTimeout">超时时间</param>
/// <param name="commandType">command类型</param>
/// <returns></returns>
public IEnumerable<T> Query<T>(string sql, object param = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null)
{
return ConnectionOption.DbConnection.Query<T>(sql, param, transaction, buffered,commandTimeout, commandType);
}
public int Execute<T>(string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null)
{
return ConnectionOption.DbConnection.Execute(sql, param, transaction, commandTimeout, commandType);
}
}
dapper还提供了扩展方法,避免写sql语句,对于增删改查更快捷的操作
public class DapperExtHelper<T> where T : class
{
public T Get(int id) {
return ConnectionOption.DbConnection.Get<T>(id);
}
public IEnumerable<T> GetAll()
{
return ConnectionOption.DbConnection.GetAll<T>();
}
public long Insert(T t)
{
return ConnectionOption.DbConnection.Insert(t);
}
public bool Update(T t)
{
return ConnectionOption.DbConnection.Update(t);
}
public bool Delete(T t)
{
return ConnectionOption.DbConnection.Delete(t);
}
public bool DeleteAll(int id)
{
return ConnectionOption.DbConnection.DeleteAll<T>();
}
}
更多操作可以娶dapper官网自行查看