PetaPoco介紹


Petapoco一

PetaPoco是一個微小的,快速的,單個文件的微型ORM,可以運行在.NET和Mono平台上。

特性:

  • 微小的,沒有依賴…單個文件,可以容易的添加進任何項目
  • 可以與嚴格的簡單的POCOS對象工作或者有特性標記的POCOS
  • 幫助方法:Inert/Delete/Update/Save 和 IsNew
  • 內嵌分頁方法
  • 事物支持
  • 良好的性能
  • 包含T4模板自動產生POCO類
  • 使用Sql查詢而不是怪異的Linq語法(汗一個)
  • 包含一個SQL Builder類產生Sql更加容易
  • 兼容SQL Server,SQL Server CE,MySql, PostgreSQL and Oracle.
  • 可以再.NET 3.5或者Mono 2.6 以上版本使用
  • 支持動態在.NET4.0和Mono 2.8
  • 開源(Apache License)

簡單介紹下用法

首先,定義一個POCO類

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

下一步,創建一個PetaPoco.Database 並且運行查詢。

View Code
// 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:

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

獲取單個記錄

View Code

分頁

View Code
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");

會返回一個Page對象:

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


Inserts, Updates and Deletes

PetaPoco 有一些幫助為insert, update 和 delete 操作.

可以有幾種不同的方式插入,先介紹最簡單的一種:

View Code
// 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(a);

// by now a.article_id will have the id of the new article

更新

View Code
// 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(a);

刪除

View Code
db.Delete("articles", "article_id", null, 123);

 

PetaPoco可以獲取多個實體,並且petapoco無侵入性。譬如

可以獲取一堆一,一對多,多對多的數據集。現在在項目中使用,十分方便,基本滿足了要求。同時也對其進行了擴展,后續會說到。

關於PetaPoco先介紹到這里,有興趣的可以去http://www.toptensoftware.com/petapoco/ 這個網站去了解,我后面爭取多寫和翻譯一些關於petapoco的文章。深入其內部機制。







免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM