.net平台性能很不错的轻型ORM类Dapper

时间:2023-03-08 15:55:25
.net平台性能很不错的轻型ORM类Dapper

dapper只有一个代码文件,完全开源,你可以放在项目里的任何位置,来实现数据到对象的ORM操作,体积小速度快。 使用ORM的好处是增、删、改很快,不用自己写sql,因为这都是重复技术含量低的工作,还有就是程序中大量的从数据库中读数据然后创建model,并为model字段赋值。这些ORM都可以轻松给你搞定。ORM给我们开发带来便利时,性能也是一个让我们不得不考虑的问题。一般的ORM性能和直接写原生的sql比都差不少,但是Dapper性能还很错,甚至和DbHelperSQL方式性能高出很多。

下载地址:https://github.com/StackExchange/dapper-dot-net

假如你喜欢原生的Sql语句,又喜欢ORM的简单,那你一定会喜欢上Dapper这款ROM。

相关dapper实际项目源码下载:

基于ASP.NET MVC5和dapper的SEO关键词按天计费系统源码

dapper ASP.NET MVC5 sql文章&博客网站源码

mvc5 dapper bootstrap2通用权限后台管理系统源码

Dapper的优势:

1,Dapper是一个轻型的ORM类。代码就一个SqlMapper.cs文件,编译后就40K的一个很小的Dll.
2,Dapper很快。Dapper的速度接近与IDataReader,取列表的数据超过了DataTable。
3,Dapper支持什么数据库。Dapper支持Mysql,SqlLite,Mssql2000,Mssql2005,Oracle等一系列的数据库,当然如果你知道原理也可以让它支持Mongo db
4,Dapper的r支持多表并联的对象。支持一对多 多对多的关系。并且没侵入性,想用就用,不想用就不用。无XML无属性。代码以前怎么写现在还怎么写。
5,Dapper原理通过Emit反射IDataReader的序列队列,来快速的得到和产生对象。性能实在高高。
6,Dapper支持net2.0,3.0,3.5,4.0。【如果想在Net2.0下使用,可以去网上找一下Net2.0下如何配置运行Net3.5即可。】
7,Dapper语法十分简单。并且无须迁就数据库的设计。

dapper的安装

nuget里面搜索Dapper

.net平台性能很不错的轻型ORM类Dapper

点击“安装”,会下载Dapper.dll,并把引用添加到项目中。

下面介绍Dapper如何使用,来进行高效开发,以下操作dapper是编译后在Net4.0下操作的例子。

1、定义一个Person类对应数据库的Person表

CREATE TABLE [Person](
[id] [int] IDENTITY(5,1) NOT NULL primary key nonclustered,
[username] [nvarchar](100) NULL,
[password] [nvarchar](100) NULL,
[age] [int] NULL,
[registerDate] [datetime] NULL,
[address] [nvarchar](150) NULL
)
public class Person
{
public int id { get; set; }
public string username { get; set; }
public string password { get; set; }
public int age { get; set; }
public DateTime registerDate { get; set; }
public string address { set; get; }
}

2、定义连接数据库字符串

public static string ConnString = "Server=.;Database=Test1;uid=sa;pwd=sa;";

3、获取id大于2的所有Person,dapper返回类型是List类型

public static List<Person> GetPersonList()
{
using (var conn = new System.Data.SqlClient.SqlConnection(ConnString))
{
conn.Open();
var a = conn.Query<Person>("select * from Person where id>@id", new { id = });
conn.Close();
return a.ToList();
}
}

这样返回的是List类型,可以充分利用linq的好处。

4、dapper批量插入数据

public static void Execute()
{
using (var conn = new SqlConnection(ConnString))
{
conn.Open();
var r=conn.Execute(@"insert Person(username, password,age,registerDate,address) values (@a, @b,@c,@d,@e)",
new [] {
new { a = , b = , c = , d = DateTime.Now, e = }
, new { a = , b = , c = , d = DateTime.Now, e = }
, new { a = , b = , c = , d = DateTime.Now, e = }
}
conn.Close();
}
);

执行上面方法会插入3条记录,这样sql可以灵活的控制,参数不用像ADO.Net那样声明每个参数,最后还要把参数集合赋值给ADO的命令。可以看出这样简洁多了。

5、dapper修改数据,update

public static bool Update()
{
using (var conn = new SqlConnection(ConnString))
{
conn.Open();
var r = conn.Execute(@"update Person set password='www.lanhuseo.com' where username=@username", new { username = });
conn.Close();
return r > ;
}
}

6、dapper删除数据

public static bool Delete()
{
using (var conn = new SqlConnection(ConnString))
{
conn.Open();
var r = conn.Execute(@"delete from Person where id=@id", new { id = });
conn.Close();
return r > ;
}
}

7、dapper使用事务

using (var conn = new SqlConnection(ConnString))
{
conn.Open();
IDbTransaction trans = conn.BeginTransaction();
int row = conn.Execute(@"update Person set password='www.lanhuseo.com' where id=@id", new { id = }, trans, null, null);
row += conn.Execute("delete from Person where id=@id", new { id = }, trans, null, null);
trans.Commit();
}

8、dapper集合批量插入

public static int InsertMultiple<T>(string sql, IEnumerable<T> entities, string connectionName = null) where T : class, new()
{
using (SqlConnection cnn = GetOpenConnection(connectionName))
{
int records = ;
using (var trans = cnn.BeginTransaction())
{
try
{
cnn.Execute(sql, entities, trans, , CommandType.Text);
}
catch (DataException ex)
{
trans.Rollback();
throw ex;
}
trans.Commit();
}
//foreach (T entity in entities)
//{
// records += cnn.Execute(sql, entity);
//}
return records;
}
}

Dapper支持集合的插入,集合提交是一句直接的插入命令,所以速度会快很多。

通过上面的实例可以看到sql语句完全是我们自己控制,对于对EF和NHibernate这些自动给我们生成sql语句的这种机制不爽的同学就有福利了,我个人觉得这个Dapper和iBatis.Net机制都差不多,都是sql语句都是完全由程序员自己写,框架自身只负责数据转换成我们需要的Model相关的对象,这样程序性能得到了保证,但是也有一个不好的地方的所有的sql语句都要自己写,比如增、删、查、改,如果一个项目有上百个表,工作量也不小,还好有代码生成器把我们解放出来,例如:Codesmith。Dapper和iBatis.Net是大的区别是,Dapper更加简单和轻量,不用像iBatis.Net配置xml文件。

我自从认识了Dapper,如果项目性能要求比较高的情况下,我会首先考虑用Dapper,Dapper简单、轻量以以对sql语句的完全控制的特性,让我感觉相见恨晚。

9、要用到DapperExtensions库

/// <summary>
/// 批量插入功能
/// </summary>
public void InsertBatch<T>(IDbConnection conn, IEnumerable<T> entityList, IDbTransaction transaction = null) where T : class
{
var tblName = string.Format("dbo.{0}", typeof(T).Name);
var tran = (SqlTransaction)transaction;
using (var bulkCopy = new SqlBulkCopy(conn as SqlConnection, SqlBulkCopyOptions.TableLock, tran))
{
bulkCopy.BatchSize = entityList.Count();
bulkCopy.DestinationTableName = tblName;
var table = new DataTable();
DapperExtensions.Sql.ISqlGenerator sqlGenerator = new SqlGeneratorImpl(new DapperExtensionsConfiguration());
var classMap = sqlGenerator.Configuration.GetMap<T>();
var props = classMap.Properties.Where(x => x.Ignored == false).ToArray();
foreach (var propertyInfo in props)
{
bulkCopy.ColumnMappings.Add(propertyInfo.Name, propertyInfo.Name);
table.Columns.Add(propertyInfo.Name, Nullable.GetUnderlyingType(propertyInfo.PropertyInfo.PropertyType) ?? propertyInfo.PropertyInfo.PropertyType);
}
var values = new object[props.Count()];
foreach (var itemm in entityList)
{
for (var i = ; i < values.Length; i++)
{
values[i] = props[i].PropertyInfo.GetValue(itemm, null);
}
table.Rows.Add(values);
}
bulkCopy.WriteToServer(table);
}
}

DapperExtensions的地址:https://github.com/tmsmith/Dapper-Extensions

参考:https://www.lanhusoft.com/Article/26.html

如果这篇文章对您有帮助,您可以打赏我

.net平台性能很不错的轻型ORM类Dapper

技术交流QQ群:15129679