8

推荐一个Dapper扩展CRUD基本操作的开源库 - chingho

 2 years ago
source link: https://www.cnblogs.com/chingho/p/17090697.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

在C#众多ORM框架中,Dapper绝对称得上微型ORM之王,Dapper以灵活、性能好而著名,同样也是支持各种数据库,但是对于一些复杂的查询,我们写原生的SQL语句问题不大,对于CRUD基本操作,我们同样也是需要写原生的SQL来实现,这个就比较麻烦了。

今天给大家推荐一个Dapper扩展库,来实现CRUD的基本操作,可以省去这些繁琐的代码,提升开发效率。

项目简介

这个是Dapper小型扩展库,通过为POCO添加基本CRUD操作,来扩展Dapper。对于复杂的查询场景,也增加了扩展。

技术架构

1、支持:支持Net 4.6+、NetStandard 2.0、NetCore 2.0+。

项目特性

1、开箱即用,使用简单;

2、为实体自动映射获取、插入、更新和删除操作;

3、支持GetList、Count、GetPage方法;

4、支持GUID、Int类型主键,其他类型可通过自定义的方式实现;

5、通过ClassMapper实现自定义映射。

项目结构

图片

使用方法

插入数据

//定义实体
Person p = new Person { Active = true, FirstName = "Foo", LastName = "Bar", DateCreated = DateTime.UtcNow };
//插入并返回id
var id = Db.Insert(p);
Assert.AreEqual(1, id);

获取单个实体

//根据id,获取实体
Person p2 = Db.Get<Person>(id);
Assert.AreEqual(id, p2.Id);

删除记录

//根据id,删除记录
Person p2 = Db.Get<Person>(id);Db.Delete(p2);
Assert.IsNull(Db.Get<Person>(id));

更新记录

//根据id,获取记录
var p2 = Db.Get<Person>(id);
//更改记录
p2.FirstName = "Baz";p2.Active = false;
//更新记录
Db.Update(p2);

获取记录列表

//获取所有记录
IEnumerable<Person> list = Db.GetList<Person>();
Assert.AreEqual(4, list.Count());

根据自动排序、获取指定的记录

//排序字段
IList<ISort> sort = new List<ISort>  {    Predicates.Sort<Person>(p => p.LastName),    Predicates.Sort<Person>("FirstName")  };
//获取指定的记录
IEnumerable<Person> list = Db.GetPage<Person>(null, sort, 0, 2);
Assert.AreEqual(2, list.Count());

获取过滤条件的记录总数

//字段过滤
var predicate = Predicates.Field<Person>(f => f.DateCreated, Operator.Lt, DateTime.UtcNow.AddDays(-5));
//获取总数
int count = Db.Count<Person>(predicate);
Assert.AreEqual(2, count);

项目地址

https://github.com/tmsmith/Dapper-Extensions

更多开源项目请查看一个专注推荐优秀.Net开源项目的榜单

- End -

文章首发于公众号【编程乐趣】,欢迎大家关注。

图片

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK