NPoco官方主頁:https://github.com/schotime/NPoco
NPoco官方簡介:Simple microORM that maps the results of a query onto a POCO object. Project based on Schotime's branch of PetaPoco。
很奇怪,Google不到任何關於NPoco的中文介紹。而我的第一篇“開局篇”竟然在前列,MY GOD!不過也不算太奇怪,因為NPoco的源起PetaPoco的中文資料就很少,這給大叔我的學習增加了好大的難度。不過好在NPoco的GitHub主頁很活躍,提問都有回復,更新也挺頻繁。所以,學習NPoco的最大障礙不是資料,只是英語了。英語啊!怨念!
以下簡介基於NPoco的官方wiki:https://github.com/schotime/NPoco/wiki
一、Standard Features
- Mapping
By default no mapping is required. It will be assumed that the table name will be the class name and the primary key will be 'Id' if its not specified with the attributes below.
這應該是ORM標准功能吧。結合T4模板,自動生成Class,很舒服。
示例:
[TableName("Users")] [PrimaryKey("UserId")] public class User { public int UserId { get;set; } [Column("emailAddress")] public string Email { get;set; } [Result] public string ExtraInfo { get;set; } [Ignore] public int Temp { get;set; } }
除了PetaPoco的 [TableName] [PrimaryKey] [Column] [Result] [Ignore] 屬性外,NPoco還增加 [Result]:
是介於普通Column與Ignore之間的一種列,不會自動被Update/Insert,但是可以手動的用SQL進行操作。[Result]
Properties marked with the Result column can be mapped into, however there properties will not be included in inserts or updates.
Note: These columns will need to be explicitly specified in the SQL. It will not be included in the auto generated SQL.
- Query Single Object
Selecting an object from the database can be done in a few different ways.
從數據庫檢索數據並轉換為Object。依然是標准的ORM功能。有以下幾種方法:
//The easiest way to load an object from the database is by passing the primary key to the SingleById<T>() method. IDatabase db = new Database("connStringName"); User u = db.SingleById<User>(3);
//Below you can see that only the where is specified. //If you don't explicitly supply the select clause it will be automatically generated for you and the where will then be appended. User u = db.Single<User>("where emailaddress = @0", "email@domain.com"); //or User u = db.Single<User>("select u.* from users u where emailaddress = @0", "email@domain.com"); //Both these methods have a 'OrDefault' method if you are unsure that the object will exist. //If it doesn't exist and you don't use the 'OrDefault' override it will throw an exception.
//There are also First<T> and FirstOfDefault<T> which will not throw an exception if more than 1 record is returned.
- Create Read Update Delete
繼續。。。
//Inserting a new record IDatabase db = new Database("connStringName"); User u = new User() { Email = "name@domain.com", LastLoggedIn = DateTime.UtcNow }; db.Insert(u);
//Reading the new record var user = db.SingleById(u.UserId); Assert.AreEqual(u.Email, user.Email);
//Updating the record //Once I have the object, I can update its properties. After calling the Update method, those changes will be persisted to the database. var user = db.SingleById(1); user.Email = "new@domain.com"; db.Update(user);
//Deleting the record //If I decide I no longer need the record I can delete it in a very similar fashion to Insert and Update.
//That is by passing the object to the Delete method. Just the primary key value can also be passed to the Delete method, however the generic type parameter will need to be specified. var user = db.SingleById(1); db.Delete(user); //or db.Delete<User>(1); - Query List
Here are some of the ways to fetch multiple rows from the database.
即檢索多條數據庫記錄到List<T>中。
// Eager Loading //1: Fetch all List<User> users = db.Fetch<User>(); //2: Fetch with criteria List<User> users = db.Fetch<User>("where isActive = 1"); //3: Fetch with raw SQL List<User> users = db.Fetch<User>("select u.* from users where u.isActive = 1");
// Lazy Loading //Warning: The following method Query<T> uses the yield keyword. It will only run the query when the results are being iterated over. //Please use the Fetch<T> method if you don't fully understand this concept. List<User> users = db.Query<User>("select u.* from users where u.isActive = 1");
- Paging
There are two main methods used for paging.
分頁幫助函數,比PetaPoco多一種。
//Page<T> is defined by: public class Page<T> { public long CurrentPage { get; set; } public long TotalPages { get; set; } public long TotalItems { get; set; } public long ItemsPerPage { get; set; } public List<T> Items { get; set; } } //Paging //You must provide an order by statement in your SQL statement so that the query knows in which order you want your data to be paged. IDatabase db = new Database("connStringName"); Page<T> pagedUsers = db.Page<User>(2, 10, "select u.* from users u order by userid");
第二種方式:
// SkipTake<T>
//The SkipTake<T> method is very similar to the Skip and Take methods in LINQ.
//It has the same number of parameters as the Page<T> method, but instead of the first parameter being the page number, it is the number of records to skip.
//The second parameter is the number of records to return after x number of records have been skipped.
//To return the same results as the Page<T> method, the query would be as follows: List<User> users = db.SkipTake<User>(10, 10, "select u.* from users u order by userid");大意是以類Paging的方法,直接返回List<T>。目前尚未用到此函數。
官方主頁上只列出了以上五條標准功能,其他PetaPoco的功能未列出,如果需要可直接查看PetaPoco的幫助。這里推薦一篇中文版的:http://www.cnblogs.com/youring2/archive/2012/06/04/2532130.html
二、Extras
以下是NPoco的擴展功能,一共13條,貌似很多啊!可惜有三條沒介紹,不知道有啥用。
目前對我很重要的就是第6條和第13條,但在使用中我遇到了一些問題,有時間的話我會單獨寫文章詳細記述。
- Query onto an existing object
- One-to-Many query helpers
- Mapping to Nested Objects query helpers
- Dictionary<string, object> and object[] queries for dynamic results
- Change tracking for updates
- Composite Primary Key support
//Composite keys can be specified by placing a comma between the two column names in the [PrimaryKey] attribute. [TableName("Users")] [PrimaryKey("UserId,UserName")] public class User { public int UserId { get; set; } public string UserName { get;set; } } //If you want to get one of these objects from the database using the SingleById group of methods then you can use an anonymous type. IDatabase db = new Database("connStringName"); var user = db.SingleById<User>(new {UserId = 1, UserName = "user"});
- Queries that returns Multiple Result Sets
- Fluent Mappings including Conventional based mappings
- Simple LINQ Queries v2+
- Version column support
- IDatabase interface
- Sql Templating
- Debugging/Profiling (MiniProfiler/Glimpse)
There are a few ways to debug/profile NPoco. They are listed below, and are commonly done by inheriting from Database and overriding a specific method. Note: Make sure you instantiate your new class (MyDb
as below) when creating a Database from then on.