.net的輕量級ORM -- PetaPoco/NPOCO架構使用說明

來源:互聯網
上載者:User

標籤:ems   sof   let   des   div   .net   架構   build   current   

.net的輕量級ORM -- PetaPoco/NPOCO架構使用說明
(具體參看:http://www.toptensoftware.com/petapoco/)

  從11年就開始嘗試使用輕量級ORM:PetaPoco,下文是基本使用方法。另外NPoco是PetaPoco的升級版,是另外一個人維護,原版PetaPoco基本不再維護。NPoco大多數用法和PetaPoco一致,另外有些額外的功能。NPoco我會考慮再寫一篇文章介紹。

  執行查詢

  首先定義POCO
  注:POCO意思是Plain Old CLR Object即指一般指帶有無參建構函式只有get set的簡單.net類:

// Represents a record in the "articles" tablepublic 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; }}

查詢

// Create a PetaPoco database objectvar 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);}

注意: Database有Fetch和Query兩個方法

Fetch返回List<T>.
而Query通過yield return 返回,使得不用遍曆記錄不用通過轉載整個資料到記憶體裡面.

注意:少量資料用Fetch更方便,大量資料而且只是單向遍曆或者返回請用Query,以節約記憶體.

返回單個值

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

返回單條記錄

var a = db.SingleOrDefault<article>("SELECT * FROM articles WHERE [email protected]", 123));

注意:當運行SingleOrDefault返回超過1條記錄會報錯

分頁查詢

注意:所有大資料量查詢請都使用這個分頁的方法,PetaPoco的分頁查詢是資料庫分頁.

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

會返回

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; }}

運行分頁方法,實際上PetaPoco會執行兩件事:

返回匹配的所有總記錄數.
得到需要的頁數的字記錄數.

注意:PetaPoco會把你的sql轉換成分頁sql,所以對sql有一定限制,請不要用select * 而且寫得sql嚴格用空格分開,避免PetaPoco不能正確地解析你的sql.

新增,更新,刪除記錄
新增

// Create the articlevar a=new article();a.title="My new article";a.content="PetaPoco was here";a.date_created=DateTime.UtcNow;// Insert itdb.Insert("articles", "article_id", a);// by now a.article_id will have the id of the new article

更新

// Get a recordvar a=db.SingleOrDefault<article>("SELECT * FROM articles WHERE [email protected]", 123);// Change ita.content="PetaPoco was here again";// Save itdb.Update("articles", "article_id", a);可以用匿名對象更新,以下是僅更新title的例子db.Update("articles", "article_id", new { title="New title" }, 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 a recordvar a=new article();a.title="My new article";a.content="PetaPoco was here";a.date_created=DateTime.UtcNow;db.Insert(a);// Update ita.content="Blah blah";db.Update(a);// Delete itdb.Delete(a);

當然也可以這樣運行

// Delete an articledb.Delete<article>("WHERE [email protected]", 123);// Update an articledb.Update<article>("SET [email protected] WHERE [email protected]", "New Title", 123);

也可以忽略某些屬性

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

使用事務

using (var trans =db.getTransaction()){    // Do transacted updates here    // Commit    trans.Complete();}

SQL Builder

var id=123;var sql=PetaPoco.Sql.Builder    .Append("SELECT * FROM articles")    .Append("WHERE [email protected]", id);if (start_date.HasValue)    sql.Append("AND date_created>[email protected]", start_date.Value);if (end_date.HasValue)    sql.Append("AND date_created<[email protected]", end_date.Value);var a=db.Query<article>(sql);

也可以使用名字命名:

sql.Append("AND date_created>[email protected] AND date_created<[email protected]",     new     {         start=DateTime.UtcNow.AddDays(-2),         end=DateTime.UtcNow     };);        

 

也可以這樣使用

var sql=PetaPoco.Sql.Builder()    .Select("*")    .From("articles")    .Where("date_created < @0", DateTime.UtcNow)    .OrderBy("date_created DESC");

 

.net的輕量級ORM -- PetaPoco/NPOCO架構使用說明

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.