接触PetaPoco已经有一段时间了,为了全面了解一下PetaPoco,刚好结合目前在做的一个项目,对常用的几个业务操作用PetaPoco进行改写,如增删改查、分页以及存储过程的调用,在文章的最后附上我测试的源码(源码有许多不规范的地方,也有冗余,只是简单地改写后为了快速通过函数功能测试,希望大家拍砖指正。)
1、 PetaPoco是C#微型ORM框架,基本无需配置,仅由单个cs文件构成,支持.net3.5 .net4.0。官方还出品了配套的T4模板用来自动生成数据库Models。官方网站:http://www.toptensoftware.com/petapoco/,截稿时PetaPoco的官方最新版本为5.0.1。
2、 从官网下载文件压缩包(另一种安装PetaPoco文件的方式见本文的最后的附录一),下载地址需要注意一下,官方给出的Github下载地址是https://github.com/toptensoftware/PetaPoco,如果你点这个地址下载下来的可能是前一个版本,也就是4.0.3,我个人是遇到这个问题了,以为下载下来的是5.0.1,其实不然,下面给出一个能下载到5.0.1的地址,也是Github上的https://github.com/toptensoftware/PetaPoco/tree/v5,打开链接之后点击右边下载zip包即可。(顺带也提醒一下,官网给出的NuGet下载地址,没有加入版本号,下载到的其实也是4.0.3,所以大家在下载的时候把版本号也加上了,具体请见本文的附录一)。另外,建议大家参与一下官网的这篇文章http://www.toptensoftware.com/Articles/137/Long-Time-No-Post-and-PetaPoco-v5,我也是看完之后才知道我下载的版本不是最新的。说明一下:我下载的时间是2014年4月3日,至于这个日期以后的会不会变化就留给大家去验证了。
3、 先建立一个类库并命名(我的叫做Controller),然后先添加一个App.config文件,创建数据库连接字符串,必须指定为providerName=”System.Data.SqlClient”。把第二步下载到的PetaPoco文件压缩包解压后把T4模板以及PetaPoco.cs文件拷贝到你的项目中,项目结构如下图所示,编辑Database.tt,如果需要自动生成视图的代码,需要加上这一句:IncludeViews = true; 保存文件后再Database.tt 文件上点击右键,运行自定义工具(可能会有一个.net版本警告,可以直接无视),就能在Database.tt下生成一个Database.cs 文件了,文件里面是什么内容,大家打开看一下就明白了。
4、 使用SingleOrDefault或者Delete的时候,参数用object和用string调用的是两个不同的接口,public T SingleOrDefault<T>(object primaryKey)和public T SingleOrDefault<T>(string sql, params object[] args),写法如下:
[WebMethod(Description = "", MessageName = "QueryOne", EnableSession = true)] public string QueryOne(object strId) { var db = Hyet.Model.DbUtils.GetInstance(); object obj = db.SingleOrDefault<Tbl_WaiterInfo>(strId); return SerializeHelper<Tbl_WaiterInfo>.Serialize(obj); } [WebMethod(Description = "", MessageName = "DeleteReal", EnableSession = true)] public string DeleteReal(object strId) { var db = Hyet.Model.DbUtils.GetInstance(); object obj = db.Delete<Tbl_WaiterInfo>(strId); return obj.ToString(); }
5、 模糊查询,用like关键字的时候需要注意下面的写法,这里特别感谢博客园网友的指点。
//注意有Like关键字用下面这种写法(写法1) //sql.Append("WHERE W.WaiterName Like '%" + strKeyword + "%' OR W.Sex Like '%" + strKeyword + "%' OR W.WaiterAccount Like '%" + strKeyword + "%' ", strKeyword); //来自博客园网友James-yu的指点(写法2) sql.Append("WHERE W.WaiterName Like @0 OR W.Sex Like @0 OR W.WaiterAccount Like @0 ", "%" + strKeyword + "%"); //不要采用下面这种方式,实现不了模糊查询 //sql.Append("WHERE W.WaiterName Like '%@0%' OR W.Sex Like '%@0%' OR W.WaiterAccount Like '%@0%' ", strKeyword);
6、 执行存储过程
db.EnableAutoSelect = false; //需要加上这么一句,是否自动添加select子句 //输入参数 var param0 = new SqlParameter("@strInput1", System.Data.SqlDbType.VarChar, 255); param0.Direction = System.Data.ParameterDirection.Input; param0.Value = strInput1; var param1 = new SqlParameter("@strInput2", System.Data.SqlDbType.NVarChar, 255); param1.Direction = System.Data.ParameterDirection.Input; param1.Value = strInput2; //输出参数 var param2 = new SqlParameter("@strOutput1", System.Data.SqlDbType.NVarChar, 255); param2.Direction = System.Data.ParameterDirection.Output; param2.Value = DBNull.Value; var param3 = new SqlParameter("@strOutput2", System.Data.SqlDbType.NVarChar, 255); param3.Direction = System.Data.ParameterDirection.Output; param3.Value = DBNull.Value; var sql = PetaPoco.Sql.Builder.Append("exec 存储过程名称 @0,@1,@2 output,@3 output", param0, param1, param2, param3); var result = db.Fetch<T>(sql); //根据实际情况替换T string str = param2.Value.ToString(); //返回值 string str = param3.Value.ToString();//返回值
7、 存储过程代码示例:
ALTER PROCEDURE [dbo].[proc_ChuChangQiuTong] @strInput1 NVARCHAR(255), @strInput2 NVARCHAR(255), @strOutput1 NVARCHAR(255) OUTPUT, @strOutput2 NVARCHAR(255) OUTPUT AS Declare @SELECT NVARCHAR(1000) ----存放动态生成的SQL语句 BEGIN SET @SELECT = 'SELECT * FROM dbo.Tbl_WaiterInfo WHERE IsDelete=0' EXEC(@SELECT) --这里执行结果是一个数据集 SET @strOutput1 = @strInput1 SET @strOutput2 = @strInput2 SELECT @strOutput1 SELECT @strOutput2 END
8、 A表(T4模板自动生成对应的A类)Join B表(T4模板自动生成对应的B类),返回结果按平常习惯来说它应该是一个数据集DataSet或者DataTable,但是,PetaPoco没有返回DataSet或者DataTable的,如Fetch<T>返回的是一个List<T>,这时候就会有麻烦了,这个T到底是写A呢还是写B呢?不用纠结,马上告诉你答案:
解决方法1(最为推荐):因为是用T4模板来自动生成数据库表或者视图的模型类,所以不建议在自动生成的代码里面做过多的扩展,否则一重新生成,之前修改的代码就会被覆盖掉了。再来看一下,T4模板生成的是partial class(MSDN给出的官方定义是这样的:分部类型定义允许将类、结构或接口的定义拆分到多个文件中),如下图所示:
接着上面的话题,首先添加一个新类,使用与T4模板生成的类相同的名字(确保名称空间也要匹配),声明为partial class,给任何Join的列添加[ResultColumn]属性,这里我们决定来partial A,把Join后B的属性加进来,代码举例如下图所示,
最后的执行代码是这样的:var result = db.Fetch<A>(sql);
项目结构如下图所示:
解决方法2(这中方法我本人没有试过,待验证):可以自己写一个类C,这个类的属性就是A和B的Join后的所有列,C类示例代码:
public class C { public string p1 { get;set; } public long p2 { get;set; } …… }
最后的执行代码:var articles = db.Fetch<C>(sql);
附录一(从NuGet安装PetaPoco,参考来自http://landyer.com/archives/138)
VS2010自带了NuGet,但是版本可能不是最新的(我的就不是)。
首先把NuGet升级到最新版本。
3. 如上图,这种情况就是需要更新《NuGet Package Manager》。如果没有出现,则说明H你的《NuGet》已经是最新的了(前提是你是VS2010),直接进入下一章吧。
4. 点击《更新》,然后按操作进行就ok了。
5. 依次打开《工具》《库程序包管理器》《程序包管理器控制台》
6. 敲入命令对可用的版本进行查询get-package –listavailable –allversion –filter petapoco,如图
7. 我要使用的是petapoco 5.0.1这一个,敲入命令进行安装install-package petapoco –version 5.0.1,如图
中间弹出对话框,直接确定,如果之后报错直接无视就行了。
8. 将当前焦点窗口转移回控制台。如下图输出,表示安装成功。
9. 上图中的《acoms》是我当前的项目,安装的时候默认要有一个打开的项目的Web的桌面的都可以。
10. PetaPoco的安装结束。
附录二(有用的帮助文档)
http://www.toptensoftware.com/petapoco/
http://landyer.com/archives/138
http://www.cnblogs.com/vento/archive/2013/02/09/2909562.html
http://www.cnblogs.com/youring2/archive/2012/06/04/2532130.html
http://www.cnblogs.com/yanxiaodi/archive/2013/03/25/2978606.html
http://www.toptensoftware.com/Articles/74/PetaPoco-Paged-Queries (针对row_number()问题)
附录三(附上我这边调试好的代码片段)
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using Hyet.Model; using Common; using PetaPoco; using System.Data.SqlClient; namespace ServicesApi.API { /// <summary> /// Waiter 的摘要说明 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。 // [System.Web.Script.Services.ScriptService] public class Waiter : System.Web.Services.WebService { [WebMethod(Description = "添加", MessageName = "Insert", EnableSession = true)] public object Insert(string strEntityInfo) { var db = Hyet.Model.DbUtils.GetInstance(); Tbl_WaiterInfo waiterInfo = SerializeHelper<Tbl_WaiterInfo>.Deserialize(strEntityInfo); return db.Insert(waiterInfo); } [WebMethod(Description = "修改", MessageName = "Update", EnableSession = true)] public string Update(string strEntityInfo) { var db = Hyet.Model.DbUtils.GetInstance(); Tbl_WaiterInfo waiterInfo = SerializeHelper<Tbl_WaiterInfo>.Deserialize(strEntityInfo); object obj = db.Update(waiterInfo); return obj.ToString(); } [WebMethod(Description = "真删", MessageName = "DeleteReal", EnableSession = true)] public string DeleteReal(object strId) { //参数用object和用string调用的是两个不同的接口,public T SingleOrDefault<T>(object primaryKey)和public T SingleOrDefault<T>(string sql, params object[] args) var db = Hyet.Model.DbUtils.GetInstance(); object obj = db.Delete<Tbl_WaiterInfo>(strId); return obj.ToString(); } [WebMethod(Description = "假删", MessageName = "DeleteNoReal", EnableSession = true)] public string DeleteNoReal(object strId) { //参数用object和用string调用的是两个不同的接口,public T SingleOrDefault<T>(object primaryKey)和public T SingleOrDefault<T>(string sql, params object[] args) var db = Hyet.Model.DbUtils.GetInstance(); object entity = db.SingleOrDefault<Tbl_WaiterInfo>(strId); Tbl_WaiterInfo waiterInfo = (Tbl_WaiterInfo)entity; waiterInfo.IsDelete = 1; object obj = db.Update(waiterInfo); return obj.ToString(); } [WebMethod(Description = "获取单个实体", MessageName = "QueryOne", EnableSession = true)] public string QueryOne(object strId) { //参数用object和用string调用的是两个不同的接口,public T SingleOrDefault<T>(object primaryKey)和public T SingleOrDefault<T>(string sql, params object[] args) var db = Hyet.Model.DbUtils.GetInstance(); object obj = db.SingleOrDefault<Tbl_WaiterInfo>(strId); return SerializeHelper<Tbl_WaiterInfo>.Serialize(obj); } [WebMethod(Description = "获取所有实体", MessageName = "QueryAll", EnableSession = true)] public string QueryAll(string strKeyword) { var db = Hyet.Model.DbUtils.GetInstance(); var sql = PetaPoco.Sql.Builder.Append("select * from Tbl_WaiterInfo where IsDelete=0"); //注意有Like关键字用下面这种写法(写法1) //if (!string.IsNullOrEmpty(strKeyword)) { sql.Append("and WaiterName like '%" + strKeyword + "%'"); } //注意有Like关键字只能用下面这种写法(写法2) if (!string.IsNullOrEmpty(strKeyword)) { sql.Append("and WaiterName like @0 ", "%" + strKeyword + "%"); } //不要采用下面这种方式,实现不了模糊查询 //if (!string.IsNullOrEmpty(strKeyword)) { sql.Append("and WaiterName like '%@0%'", strKeyword); } sql.Append("order by WaiterName asc"); object obj = db.Fetch<Tbl_WaiterInfo>(sql); return SerializeHelper<Tbl_WaiterInfo>.Serialize(obj); } [WebMethod(Description = "分页获取实体", MessageName = "QueryPage", EnableSession = true)] public string QueryPage(long pageIndex, long pageSize, string strKeyword) { var db = Hyet.Model.DbUtils.GetInstance(); var sql = PetaPoco.Sql.Builder.Append("select * from Tbl_WaiterInfo where IsDelete=0"); //注意有Like关键字用下面这种写法(写法1) //if (!string.IsNullOrEmpty(strKeyword)) { sql.Append("and WaiterName like '%" + strKeyword + "%'"); } //注意有Like关键字只能用下面这种写法(写法2) if (!string.IsNullOrEmpty(strKeyword)) { sql.Append("and WaiterName like @0 ", "%" + strKeyword + "%"); } //不要采用下面这种方式,实现不了模糊查询 //if (!string.IsNullOrEmpty(strKeyword)) { sql.Append("and WaiterName like '%@0%'", strKeyword); } sql.Append("order by WaiterName asc"); object obj = db.Page<Tbl_WaiterInfo>(pageIndex, pageSize, sql); return SerializeHelper<Tbl_WaiterInfo>.Serialize(obj); } [WebMethod(Description = "获取记录总数", MessageName = "GetCount", EnableSession = true)] public string GetCount() { var db = Hyet.Model.DbUtils.GetInstance(); object obj = db.ExecuteScalar<long>("select Count(*) from Tbl_WaiterInfo"); return obj.ToString(); } [WebMethod(Description = "判断是否存在", MessageName = "CheckExist", EnableSession = true)] public string CheckExist(object strId) { var db = Hyet.Model.DbUtils.GetInstance(); object obj = db.Exists<Tbl_WaiterInfo>(strId); return obj.ToString(); } [WebMethod(Description = "执行事务", MessageName = "DoTrans", EnableSession = true)] public string DoTrans(string strEntityInfo1, string strEntityInfo2) { var db = Hyet.Model.DbUtils.GetInstance(); db.BeginTransaction(); try { db.CompleteTransaction(); return "success"; } catch (Exception) { db.AbortTransaction(); return "faild"; } } [WebMethod(Description = "执行存储过程(只有输入参数)", MessageName = "ProcInput", EnableSession = true)] public string ProcInput(object strInput) { var db = Hyet.Model.DbUtils.GetInstance(); db.EnableAutoSelect = false; //一定要加上这句 //注意下面这种写法Input var param1 = new SqlParameter("@strInput1", System.Data.SqlDbType.NVarChar, 255); param1.Direction = System.Data.ParameterDirection.Input; param1.Value = strInput; var sql = PetaPoco.Sql.Builder.Append("exec proc_KeXuanZeRenRen @0", param1); object obj = db.Fetch<Tbl_WaiterInfo>(sql); return SerializeHelper<List<Tbl_WaiterInfo>>.Serialize(obj); } [WebMethod(Description = "执行存储过程(只有输出参数)", MessageName = "ProcOutput", EnableSession = true)] public string ProcOutput() { var db = Hyet.Model.DbUtils.GetInstance(); db.EnableAutoSelect = false; //一定要加上这句,是否自动添加select子句 //不要用 var param1 = new SqlParameter() { Direction = ParameterDirection.Output, SqlDbType = SqlDbType.NVarChar, Value = DBNull.Value }; //不要用 var param2 = new SqlParameter() { Direction = ParameterDirection.Output, SqlDbType = SqlDbType.NVarChar, Value = DBNull.Value }; //注意下面这种写法Output var param1 = new SqlParameter("@strOutput1", System.Data.SqlDbType.NVarChar, 255); param1.Direction = System.Data.ParameterDirection.Output; param1.Value = DBNull.Value; var param2 = new SqlParameter("@strOutput2", System.Data.SqlDbType.NVarChar, 255); param2.Direction = System.Data.ParameterDirection.Output; param2.Value = DBNull.Value; var sql = PetaPoco.Sql.Builder.Append("exec proc_TestOutput @0 output,@1 output", param1, param2); db.Execute(sql); string str1 = param1.Value.ToString(); string str2 = param2.Value.ToString(); return str1; } [WebMethod(Description = "执行存储过程(输入输出参数)", MessageName = "ProcInputOutput", EnableSession = true)] public string ProcInputOutput(object strInput) { var db = Hyet.Model.DbUtils.GetInstance(); db.EnableAutoSelect = false; //一定要加上这句,是否自动添加select子句 //注意下面这种写法Input var param1 = new SqlParameter("@strInput1", System.Data.SqlDbType.NVarChar, 255); param1.Direction = System.Data.ParameterDirection.Input; param1.Value = strInput; //注意下面这种写法Output var param2 = new SqlParameter("@strOutput1", System.Data.SqlDbType.NVarChar, 255); param2.Direction = System.Data.ParameterDirection.Output; param2.Value = DBNull.Value; var param3 = new SqlParameter("@strOutput2", System.Data.SqlDbType.NVarChar, 255); param3.Direction = System.Data.ParameterDirection.Output; param3.Value = DBNull.Value; var sql = PetaPoco.Sql.Builder.Append("exec proc_TestInputOutPut @0, @1 output, @2 output", param1, param2, param3); db.Execute(sql); string str1 = param2.Value.ToString(); string str2 = param3.Value.ToString(); return str1; } [WebMethod(Description = "执行存储过程(输入输出参数)", MessageName = "ProcInputOutput2", EnableSession = true)] public string ProcInputOutput2(object strServiceId, object strKeyword, object strWaiterId1, object strWaiterId2, object strWaiterId3, object strWaiterId4, object pageSize, object pageIndex) { var db = Hyet.Model.DbUtils.GetInstance(); db.EnableAutoSelect = false; //一定要加上这句,是否自动添加select子句 //注意下面这种写法Input var param1 = new SqlParameter("@strServiceId", System.Data.SqlDbType.VarChar, 255); param1.Direction = System.Data.ParameterDirection.Input; param1.Value = strServiceId; var param2 = new SqlParameter("@strKeyword", System.Data.SqlDbType.NVarChar, 255); param2.Direction = System.Data.ParameterDirection.Input; param2.Value = strKeyword; var param3 = new SqlParameter("@strWaiterId1", System.Data.SqlDbType.NVarChar, 255); param3.Direction = System.Data.ParameterDirection.Input; param3.Value = strWaiterId1; var param4 = new SqlParameter("@strWaiterId2", System.Data.SqlDbType.NVarChar, 255); param4.Direction = System.Data.ParameterDirection.Input; param4.Value = strWaiterId2; var param5 = new SqlParameter("@strWaiterId3", System.Data.SqlDbType.NVarChar, 255); param5.Direction = System.Data.ParameterDirection.Input; param5.Value = strWaiterId3; var param6 = new SqlParameter("@strWaiterId4", System.Data.SqlDbType.NVarChar, 255); param6.Direction = System.Data.ParameterDirection.Input; param6.Value = strWaiterId4; var param7 = new SqlParameter("@pageSize", System.Data.SqlDbType.NVarChar, 255); param7.Direction = System.Data.ParameterDirection.Input; param7.Value = pageSize; var param8 = new SqlParameter("@pageIndex", System.Data.SqlDbType.NVarChar, 255); param8.Direction = System.Data.ParameterDirection.Input; param8.Value = pageIndex; //注意下面这种写法Output var param9 = new SqlParameter("@strOutput1", System.Data.SqlDbType.NVarChar, 255); param9.Direction = System.Data.ParameterDirection.Output; param9.Value = DBNull.Value; var sql = PetaPoco.Sql.Builder.Append("exec proc_ChuChangQiuTong @0,@1,@2,@3,@4,@5,@6,@7,@8 output", param1, param2, param3, param4, param5, param6, param7, param8, param9); var result = db.Fetch<Tbl_WaiterInfo>(sql); string str9 = param9.Value.ToString(); return str9; } [WebMethod(Description = "可选出场球童", MessageName = "SelectChuChangQiuTong", EnableSession = true)] public void SelectChuChangQiuTong(string strKeyword, string strWaiterId1, string strWaiterId2, string strWaiterId3, string strWaiterId4, int pageSize, int pageIndex) { var db = Hyet.Model.DbUtils.GetInstance(); var sql = PetaPoco.Sql.Builder.Append("SELECT * FROM ("); sql.Append("SELECT UniqueID,WaiterName,WaiterAccount,IsDelete,Sex,WorkStautsName,WorkLeaveName FROM dbo.View_WaiterInfo WHERE IsDelete=0 "); sql.Append("AND UniqueID NOT IN (SELECT WaiterInfoID FROM dbo.View_ServiceWaiters WHERE ServiceEnd IS NULL) "); //过滤已经分配设备的球童 sql.Append("AND UniqueID IN (SELECT DutyWaiterID FROM dbo.Tbl_Equipment WHERE DutyWaiterID IS NOT NULL) "); //过滤掉已经选择的第1\2\3\4个球童 if (!string.IsNullOrEmpty(strWaiterId1)) { sql.Append("AND UniqueID<>'@0' ", strWaiterId1); } if (!string.IsNullOrEmpty(strWaiterId2)) { sql.Append("AND UniqueID<>'@0' ", strWaiterId2); } if (!string.IsNullOrEmpty(strWaiterId3)) { sql.Append("AND UniqueID<>'@0' ", strWaiterId3); } if (!string.IsNullOrEmpty(strWaiterId4)) { sql.Append("AND UniqueID<>'@0' ", strWaiterId4); } sql.Append(") W "); sql.Append("INNER JOIN "); sql.Append("("); sql.Append("SELECT UniqueID AS EquipmentUniqueID,EquipmentName,EquipmentNo,MobileNumber,"); sql.Append("DutyWaiterID,UseStatus FROM dbo.Tbl_Equipment WHERE UseStatus=1 AND IsDelete=0"); sql.Append(") E "); sql.Append("ON W.UniqueID = E.DutyWaiterID "); //模糊查询 if (!string.IsNullOrEmpty(strKeyword)) { //注意有Like关键字用下面这种写法(写法1) //sql.Append("WHERE W.WaiterName Like '%" + strKeyword + "%' OR W.Sex Like '%" + strKeyword + "%' OR W.WaiterAccount Like '%" + strKeyword + "%' ", strKeyword); //来自博客园网友James-yu的指点(写法2) sql.Append("WHERE W.WaiterName Like @0 OR W.Sex Like @0 OR W.WaiterAccount Like @0 ", "%" + strKeyword + "%"); //不要采用下面这种方式,实现不了模糊查询 //sql.Append("WHERE W.WaiterName Like '%@0%' OR W.Sex Like '%@0%' OR W.WaiterAccount Like '%@0%' ", strKeyword); } //结果排序 sql.Append("ORDER BY W.WaiterAccount ASC"); Page<Tbl_WaiterInfo> page = db.Page<Tbl_WaiterInfo>(pageIndex, pageSize, sql); List<Tbl_WaiterInfo> list = page.Items; string str = db.LastCommand; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Runtime.Serialization.Json; namespace Common { /// <summary> /// XML序列化助手类 /// </summary> public class SerializeHelper<T> { public static string Serialize(object obj) { if (obj == null) return null; using (MemoryStream memoryStream = new MemoryStream()) { DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(obj.GetType()); dataContractJsonSerializer.WriteObject(memoryStream, obj); return Encoding.UTF8.GetString(memoryStream.ToArray()); } } public static T Deserialize(string str) { using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(str))) { DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(T)); return (T)dataContractJsonSerializer.ReadObject(memoryStream); } } } }