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.html
github:https://github.com/tmsmith/Dapper-Extensionsios
若不熟悉Dapper的,請移步:git
後續文檔翻譯github
下面是對他的用法的描述,也就是對項目文檔的翻譯。若是讀者英文不錯能夠直接看原版文檔,見github。sql
Dapper Extensions是github上的一個開源庫是對StackOVerflow開發的Dapper ORM的一個擴展。它增長了基礎的CRUD操做((Get, Insert, Update, Delete)),對更高級的查詢場景,該類庫還提供了一套謂詞系統。它的目標是保持POCOs的純淨,不須要額外的attributes和類的繼承。數據庫
自定義映射請參見 ClassMapper架構
Nuget:
http://nuget.org/List/Packages/DapperExtensionsapp
PM> Install-Package DapperExtensions
pernson POCO的定義ide
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)