近端时间从推酷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"); } } } }
未完待续