Dapper Extensions is a small library that complements Dapper by adding basic CRUD operations (Get, Insert, Update, Delete) for your POCOs. For more advanced querying scenarios, Dapper Extensions provides a predicate system. The goal of this library is to keep your POCOs pure by not requiring any attributes or base class inheritance.
github:https://github.com/tmsmith/Dapper-Extensions
下面是对他的用法的描述,也就是对项目文档的翻译。如果读者英文不错可以直接看原版文档,见github。
Dapper Extensions是github上的一个开源库是对StackOVerflow开发的Dapper ORM的一个扩展。它增加了基础的CRUD操作((Get, Insert, Update, Delete)),对更高级的查询场景,该类库还提供了一套谓词系统。它的目标是保持POCOs的纯净,不需要额外的attributes和类的继承。
自定义映射请参见 ClassMapper
Nuget:
http://nuget.org/List/Packages/DapperExtensions
PM> Install-Package DapperExtensions
pernson POCO的定义
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(); }
//返回dynamic类型,若主键为单,返回主键值,若主键为复合的,返回IDictionary<string,object> public static dynamic Insert<T>(this IDbConnection connection, T entity, IDbTransaction transaction = null, int? commandTimeout = null) where T : class
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" }; //返回o 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 = _connection.Get<Person>(personId); person.LastName = "Baz"; cn.Update(person); cn.Close(); }
using (SqlConnection cn = new SqlConnection(_connectionString)) { cn.Open(); Person person = _connection.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(); }
Generated 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(); }
Generated SQL
SELECT COUNT(*) Total FROM [Person] WHERE ([Person].[DateCreated] < @DateCreated_0)
相关博客: