Dapper是一款轻量级ORM框架,为解决网站访问流量极高而产生的性能问题而构造,主要通过执行TSQL表达式而实现数据库的CQRS。
如果你在项目中遇到性能访问问题,选择Dapper作为ORM框架可能是明智之举,当然也可以使用Entity Framework或NHibernate来处理大数据访问及关系映射。
轻量:只有一个文件(SqlMapper.cs),编译完成之后只有140K。
速度快:Dapper的速度接近于IDataReader,取列表的数据超过了DataTable。
支持多种数据库:Dapper可以在所有Ado.Net Providers下工作,包括sqlLite、Oracle、MySQL、SQL Server。
可以映射一对一、一对多、多对多等各种关系。
性能高:通过Emit反射IDataReader的序列队列,来快速的得到和产生对象,性能不错。
支持Framework2.0、3.0、3.5、4.0、4.5。
匿名类插入
var result = mySqlConnection.Execute(
"Insert into Users values (@UserName, @Email, @Address)",
new { UserName = "Tom", Email = "747954712@qq.com", Address = "北京" }
);
if (result > 0)
{
Console.WriteLine("插入成功!");
}
else
{
Console.WriteLine("插入失败!");
}
实体类插入
User user = new User()
{
UserName = "tim",
Email = "[email protected]",
Address = "北京"
};
var result = mySqlConnection.Execute(sqlCommandText,user);
if (result > 0)
{
Console.WriteLine("插入成功!");
}
else
{
Console.WriteLine("插入失败!");
}
插入对象改为对象集合
var result = mySqlConnection.Execute("insert into Users values(@UserName,@Email,@Address)", userList);
var query = mySqlConnection.Query("SELECT * FROM Users");
query.AsList().ForEach(p =>
{
Console.WriteLine("Id:"+p.UserId+" UserName:"+p.UserName+" Email:"+p.Email+" Address:"+p.Address);
});
匿名类
var result = mySqlConnection.Execute("update Users set UserName='Tim',Address='上海' where UserId=@UserId", new { UserId = 2 });
同样实体类
User user = new User();
user.UserName = "张无忌";
user.UserId = 1;
user.Address="上海";
var result = mySqlConnection.Execute("update Users set UserName=@UserName,Address=@Address where UserId=@UserId", user);
使用键值对更新
Liststring, object>> keys = new Liststring, object>>();
keys.Add(new KeyValuePair<string, object>("@UserName", "风清扬"));
keys.Add(new KeyValuePair<string, object>("@UserId", 2));
var result = mySqlConnection.Execute("update Users set UserName=@UserName where UserId=@UserId", keys);
匿名类
var result = mySqlConnection.Execute("delete from Users where UserId=@UserId", new { UserId = 3 });
实体类
User user = new User();
user.UserId = 4;
var result = connection.Execute("delete from Users where UserId=@UserId", user);