PetaPoco 筆記

PetaPoco是一款適用於.Net 和Mono的微小、快速、單文件的微型ORM。git

PetaPoco有如下特點:github

  • 微小,沒有依賴項……單個的C#文件能夠方便的添加到任何項目中。
  • 工做於嚴格的沒有裝飾的Poco類,和幾乎所有加了特性的Poco類
  • Insert/Delete/Update/Save and IsNew 等幫助方法。
  • 分頁支持:自動獲得總行數和數據
  • 支持簡單的事務
  • 更好的支持參數替換,包括從對象屬性中抓取命名的參數。
  • 很好的性能,剔除了Linq,並經過Dynamic方法快速的爲屬性賦值
  • T4模板自動生成Poco類
  • 查詢語言是Sql……不支持彆扭的fluent或Linq語法(仁者見仁,智者見智)
  • 包含一個低耦合的Sql Builder類,讓內聯的Sql更容易書寫
  • 爲異常信息記錄、值轉換器安裝和數據映射提供鉤子。(Hooks for logging exceptions, installing value converters and mapping columns to properties without attributes.)
  • 兼容SQL Server, SQL Server CE, MySQL, PostgreSQL and Oracle。
  • 能夠在.NET 3.5 或Mono 2.6或更高版本上運行
  • 在.NET 4.0 和Mono 2.8下支持dynamic
  • NUnit單元測試
  • 開源(Apache License)
  • 全部功能大約用了1500行代碼

 

能夠從這裏得到PetaPoco:

 

建立PetaPoco對象,並執行查詢:

// Create a PetaPoco database object
var db=new PetaPoco.Database("connectionStringName");

// Show all articles    
foreach (var a in db.Query<article>("SELECT * FROM articles"))
{
    Console.WriteLine("{0} - {1}", a.article_id, a.title);
}

  獲得一個scalar:

long count=db.ExecuteScalar<long>("SELECT Count(*) FROM articles");

  獲得一行記錄:

var a = db.SingleOrDefault<article>("SELECT * FROM articles WHERE article_id=@0", 123));

獲取分頁數據(將獲取一個PageFetch對象):

  PetaPoco分頁執行過程:

var result=db.Page<article>(1, 20, // <-- page number and items per page
        "SELECT * FROM articles WHERE category=@0 ORDER BY date_posted DESC", "coolstuff");

    1.生成並執行一個查詢,獲取匹配的數據行數。web

    2.修改原始的查詢語句,只能獲得全部匹配的一個子集。數據庫

    pageFetch對象:一個展現單頁數據和分頁控制的類。app

public class Page<T> where T:new()
{
    public long CurrentPage { get; set; }
    public long ItemsPerPage { get; set; }
    public long TotalPages { get; set; }
    public long TotalItems { get; set; }
    public List<T> Items { get; set; }
}

獲取數據的方式Query 和 Fetch:

  Fetch返回一個一個POCO類的List<>,而Query使用迭代全部數據,可是這些數據沒有被加載到內存中。 ide

  不帶查詢的命令:

db.Execute("DELETE FROM articles WHERE draft<>0");

  Inserts、Updates 和 Deletes:

// Create the article
var a=new article();
a.title="My new article";
a.content="PetaPoco was here";
a.date_created=DateTime.UtcNow;

// Insert it
db.Insert("articles", "article_id", a);

// by now a.article_id will have the id of the new article
// Get a record
var a=db.SingleOrDefault<article>("SELECT * FROM articles WHERE article_id=@0", 123);

// Change it
a.content="PetaPoco was here again";

// Save it
db.Update("articles", "article_id", a);
db.Update("articles", "article_id", new { title="New title" }, 123);
// Delete an article extracting the primary key from a record
db.Delete("articles", "article_id", a);

// Or if you already have the ID elsewhere
db.Delete("articles", "article_id", null, 123); 

修飾POCO類:

// Represents a record in the "articles" table
[PetaPoco.TableName("articles")]
[PetaPoco.PrimaryKey("article_id")]
public class article
{
    public long article_id { get; set; }
    public string title { get; set; }
    public DateTime date_created { get; set; }
    public bool draft { get; set; }
    public string content { get; set; }
} 

  簡化後的insert、update、delete:

// Insert a record
var a=new article();
a.title="My new article";
a.content="PetaPoco was here";
a.date_created=DateTime.UtcNow;
db.Insert(a);

// Update it
a.content="Blah blah";
db.Update(a);

// Delete it
db.Delete(a);

  delete和update的其它方式:

// Delete an article
db.Delete<article>("WHERE article_id=@0", 123);

// Update an article
db.Update<article>("SET title=@0 WHERE article_id=@1", "New Title", 123);

  忽略某列:

public class article
{
    [PetaPoco.Ignore]
    public long SomeCalculatedFieldPerhaps
    { 
        get; set; 
    }
}

  使用類和列的屬性來指明哪些列須要映射:

// Represents a record in the "articles" table
[PetaPoco.TableName("articles")]
[PetaPoco.PrimaryKey("article_id")]
[PetaPoco.ExplicitColumns]
public class article
{
    [PetaPoco.Column]publiclong article_id { get; set;}
    [PetaPoco.Column]publicstring title { get; set;}
    [PetaPoco.Column]publicDateTime date_created { get; set;}
    [PetaPoco.Column]public bool draft { get; set;}
    [PetaPoco.Column]publicstring content { get; set;}
} 

T4 模板:

  • PetaPoco.Core.ttinclude - includes all the helper routines for reading the DB schema(數據庫模式)
  • PetaPoco.Generator.ttinclude - the actual template that defines what's generated(實體模板)
  • Database.tt - the template itself that includes various settings and includes the two other ttinclude files.(模板自己)

  use the template:

  1. Add the three files to you C# project
  2. Make sure you have a connection string and provider name set in your app.config or web.config file
  3. Edit ConnectionStringName property in Records.tt (ie: change it from "jab" to the name of your connection string)
  4. Save Database.tt.

自動的Select語句:

  運行一個不以select開頭的查詢, PetaPoco會自動的將它加上。post

IsNew 和Save 方法:

  IsNew:檢測是否爲新增。性能

  Save:根據判斷的結果執行Insert或Update。單元測試

事務:

using (var scope=db.Transaction)
{
    // Do transacted updates here

    // Commit
    scope.Complete();
}

注意:爲了使用事務,全部操做都須要相同的PetaPoco Database對象實例。測試

相關文章
相關標籤/搜索