在C#众多ORM框架中,Dapper绝对称得上微型ORM之王,Dapper以灵活、性能好而著名,同样也是支持各种数据库,但是对于一些复杂的查询,我们写原生的SQL语句问题不大,对于CRUD基本操作,我们同样也是需要写原生的SQL来实现,这个就比较麻烦了。
今天给大家推荐一个Dapper扩展库,来实现CRUD的基本操作,可以省去这些繁琐的代码,提升开发效率。
项目简介
这个是Dapper小型扩展库,通过为POCO添加基本CRUD操作,来扩展Dapper。对于复杂的查询场景,也增加了扩展。
技术架构
1、支持:支持Net 4.6+、NetStandard 2.0、NetCore 3.1+。
项目特性
1、开箱即用,使用简单;
2、为实体自动映射获取、插入、更新和删除操作;
3、支持GetList、Count、GetPage方法;
4、支持GUID、Int类型主键,其他类型可通过自定义的方式实现;
5、通过ClassMapper实现自定义映射。
项目结构
使用方法
安装
NuGet地址为:https://www.nuget.org/packages/DapperExtensions
PM> Install-Package DapperExtensions
案例
定义相关的实体类
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public bool Active { get; set; }
public DateTime DateCreated { get; set; }
}
获取单个对象
using (SqlConnection cn = new SqlConnection(_connectionString))
{
cn.Open();
int personId = 1;
Person person = cn.Get<Person>(personId);
cn.Close();
}
简单写入操作
using (SqlConnection cn = new SqlConnection(_connectionString))
{
cn.Open();
Person person = new Person { FirstName = "Foo", LastName = "Bar" };
int id = cn.Insert(person);
cn.Close();
}
高级插入操作(组合键)
public class Car
{
public int ModelId { get; set; }
public int Year { get; set; }
public string Color { get; set; }
}
using (SqlConnection cn = new SqlConnection(_connectionString))
{
cn.Open();
Car car = new Car { Color = "Red" };
var multiKey = cn.Insert(car);
cn.Close();
int modelId = multiKey.ModelId;
int year = multiKey.Year;
}
简单更新操作
using (SqlConnection cn = new SqlConnection(_connectionString))
{
cn.Open();
int personId = 1;
Person person = cn.Get<Person>(personId);
person.LastName = "Baz";
cn.Update(person);
cn.Close();
}
简单删除操作
using (SqlConnection cn = new SqlConnection(_connectionString))
{
cn.Open();
Person person = cn.Get<Person>(1);
cn.Delete(person);
cn.Close();
}
获取集合操作(带参数)
using (SqlConnection cn = new SqlConnection(_connectionString))
{
cn.Open();
var predicate = Predicates.Field<Person>(f => f.Active, Operator.Eq, true);
IEnumerable<Person> list = cn.GetList<Person>(predicate);
cn.Close();
}
生成的相关sql语句
SELECT
[Person].[Id]
, [Person].[FirstName]
, [Person].[LastName]
, [Person].[Active]
, [Person].[DateCreated]
FROM [Person]
WHERE ([Person].[Active] = @Active_0)
获取记录总数(带过滤条件)
using (SqlConnection cn = new SqlConnection(_connectionString))
{
cn.Open();
var predicate = Predicates.Field<Person>(f => f.DateCreated, Operator.Lt, DateTime.UtcNow.AddDays(-5));
int count = cn.Count<Person>(predicate);
cn.Close();
}
生成的相关sql语句
SELECT
COUNT(*) Total
FROM [Person]
WHERE ([Person].[DateCreated] < @DateCreated_0)
项目地址
https://github.com/tmsmith/Dapper-Extensions