近端時間從推酷app上了解到C#輕微型的ORM框架--PetaPoco。從github Dapper 開源項目可以看到PetaPoco排第四
以下是網友根據官方介紹翻譯,這里貼出來。
PetaPoco是一款適用於.Net 和Mono的微小、快速、單文件的微型ORM。
PetaPoco有以下特色:
- 微小,沒有依賴項……單個的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?
因為中國使用win7系統的比較多,然后win7自帶.net3.5框架,所以筆者從nuget下載了4.0.3版本的PetaPoco
獲取地址:
可以和筆者一樣安裝4.0.3版本
如下圖,回車即可
安裝之后,如果你是.net3.5的編譯環境,請關閉關閉dynamic支持:
1、打開項目屬性
2、切換到“生成”選項卡
3、在“條件編譯符號”添加PETAPOCO_NO_DYNAMIC
添加應用程序配置文件app.config
在文件里面填寫sql鏈接參數:
我這里用的是SqlServer數據庫
<?xml version="1.0" encoding="utf-8" ?> <configuration> <connectionStrings> <add name="connectionString" connectionString="Data Source=.\sql2008;Initial Catalog=test;User ID=sa;Password=123" providerName="System.Data.SqlClient"/> </connectionStrings> </configuration>
然后在T4模板中,填上剛才加的鏈接參數,一保存就可以自動生成對應的實體
如圖
下面貼出一部分測試代碼
using PetaPocoDemo.Models; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace PetaPocoDemo { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //創建一個petapoco對象 var db = new PetaPoco.Database("connectionString"); //遍歷查詢文章表 foreach (var a in db.Query<article>("select * from article")) { MessageBox.Show(a.article_id + "-------" + a.title); } //返回一個scalar數量 var count = db.ExecuteScalar<int>("select count(*) from article"); MessageBox.Show("count:" + count.ToString()); //返回一行記錄 var row = db.SingleOrDefault<article>("select * from article where article_id='1'"); MessageBox.Show(row.content); //插入記錄 var newArticle = new article(); newArticle.article_id = 2; newArticle.title = "綠書"; newArticle.content = "可持續發展綠色內容"; newArticle.date_created = DateTime.UtcNow; if (Convert.ToInt32(db.Insert("article", "article_id",false, newArticle)) > 0) { MessageBox.Show("sucess"); } else { MessageBox.Show("fail"); } } } }
未完待續