PetaPoco初體驗(轉)
?
大部分轉自:?http://landyer.com/archives/138
PetaPoco?C#微型ORM框架,基本無需配置,僅由單個cs文件構成,支持.net3.5 .net4.0。
截稿時PetaPoco的官方最新版本為5.0.1。我不采用5.0.1版本,因為我用的是.net3.5,而5.0.1的版本中用到了一個類System.Tuple,這個類是從.net4.0才開始有的。(當然也可以自己實現這個類,不過像我這樣的初學者還是算了吧)。
NuGet圖形界面中默認列出的只有最新版本,一裝就是5.0.1,?那就是使用NuGet命令行。
1.依次打開《工具》《庫程序包管理器》《程序包管理器控制臺》
2.敲入命令對可用的版本進行查詢get-package –listavailable –allversion –filter petapoco,如圖
3.敲入命令進行安裝install-package petapoco –version 4.0.3
?
配置PetaPoco
現在又遇到一個問題,使用Ctrl+Shift+B編譯項目的時候報錯,說dynamic神馬的不存在。
這是因為Dynamic也是.net4.0的。PetaPoco官方提供了一個編譯時的選項來開啟&關閉對dynamic的支持。
下面來進行編譯選項的設置:
- 在項目上《右鍵》《屬性》
- 選擇左側tab的第二項《生成》,在《條件編譯符號》中輸入PETAPOCO_NO_DYNAMIC
- 保存,再次Ctrl+Shift+B,進行編譯。這次就OK了。
?
配置PetaPoco T4模板
-
打開
Database.tt
文件
ConnectionStringName = "WorkDemo"; // Uses last connection string in config if not specifiedNamespace = "WorkDemo.Tests.Models";RepoName = "PPUtils"; //輔助類的名字
?
PetaPoco使用示例
? ? 一對多 和 多對一
-
為Account增加一個額外的屬性AccountUsers
- 為Account_User增加一個額外的屬性Account
- 將Account和Account_User進行關聯
public partial class Account{[PetaPoco.Ignore]public List<Account_User> AccountUsers { get; set; } }public partial class Account_User{[PetaPoco.Ignore]public Account Account { get; set; }}//public class UserAccountRelator{private Dictionary<long, Account> accounts = new Dictionary<long, Account>();public Account_User MapIt(Account account, Account_User user){Account accountExisting;if (accounts.TryGetValue(account.Id, out accountExisting)){account = accountExisting;}elseaccounts.Add(account.Id, account);user.Account = account;return user;}}//public class AccountUserRelator{public Account current;public Account MapIt(Account account, Account_User user){if (account == null)return current;if (current != null && current.Id == account.Id){current.AccountUsers.Add(user);return null;}var prev = current;current = account;current.AccountUsers = new List<Account_User>();current.AccountUsers.Add(user);return prev;}}
? ? 查詢:
var users = db.Fetch<Account, Account_User, Account_User>(new UserAccountRelator().MapIt,"select * from Account A left join Account_User AU on AU.AccountId=A.Id ");foreach (Account_User user in users){Console.WriteLine("{0} - {1}", user.Id, user.UserName);}var accounts = db.Fetch<Account, Account_User, Account>(new AccountUserRelator().MapIt,"select * from Account A left join Account_User AU on AU.AccountId=A.Id ");foreach (Account acc in accounts){Console.WriteLine("{0} - {1}", acc.Id, acc.Name);}
?