近端時間從推酷app上了解到C#輕微型的ORM框架--PetaPoco。從github Dapper 開源項目能夠看到PetaPoco排第四git
如下是網友根據官方介紹翻譯,這裏貼出來。github
PetaPoco是一款適用於.Net 和Mono的微小、快速、單文件的微型ORM。sql
PetaPoco有如下特點:數據庫
如何獲取PetaPoco?app
由於中國使用win7系統的比較多,而後win7自帶.net3.5框架,因此筆者從nuget下載了4.0.3版本的PetaPoco
框架
獲取地址:ide
NuGet - http://nuget.org/List/Packages/PetaPoco性能
GitHub - https://github.com/toptensoftware/petapoco單元測試
能夠和筆者同樣安裝4.0.3版本測試
以下圖,回車便可
安裝以後,若是你是.net3.5的編譯環境,請關閉關閉dynamic支持:
一、打開項目屬性
二、切換到「生成」選項卡
三、在「條件編譯符號」添加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"); } } } }
未完待續