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:
一、Standard Features
- 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]:
[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. 是介于普通Column与Ignore之间的一种列,不会自动被Update/Insert,但是可以手动的用SQL进行操作。 - 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
() method.IDatabase db = new Database("connStringName");User u = db.SingleById (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
("where emailaddress = @0", "email@domain.com");//orUser u = db.Single ("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
and FirstOfDefault which will not throw an exception if more than 1 record is returned. - 继续。。。
//Inserting a new recordIDatabase db = new Database("connStringName");User u = new User() { Email = "name@domain.com", LastLoggedIn = DateTime.UtcNow};db.Insert(u);
//Reading the new recordvar 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);//ordb.Delete
(1); - Here are some of the ways to fetch multiple rows from the database.即检索多条数据库记录到List<T>中。
// Eager Loading//1: Fetch allList
users = db.Fetch ();//2: Fetch with criteriaList users = db.Fetch ("where isActive = 1");//3: Fetch with raw SQLList users = db.Fetch ("select u.* from users where u.isActive = 1"); // Lazy Loading//Warning: The following method Query
uses the yield keyword. It will only run the query when the results are being iterated over. //Please use the Fetch method if you don't fully understand this concept.List users = db.Query ("select u.* from users where u.isActive = 1"); - There are two main methods used for paging. 分页帮助函数,比PetaPoco多一种。
//Page
is defined by:public class Page { public long CurrentPage { get; set; } public long TotalPages { get; set; } public long TotalItems { get; set; } public long ItemsPerPage { get; set; } public List 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 pagedUsers = db.Page (2, 10, "select u.* from users u order by userid"); 第二种方式:
// SkipTake
//The SkipTake method is very similar to the Skip and Take methods in LINQ. //It has the same number of parameters as the Page 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 method, the query would be as follows:List users = db.SkipTake (10, 10, "select u.* from users u order by userid"); 大意是以类Paging的方法,直接返回List<T>。目前尚未用到此函数。
官方主页上只列出了以上五条标准功能,其他PetaPoco的功能未列出,如果需要可直接查看PetaPoco的帮助。这里推荐一篇中文版的:
二、Extras
以下是NPoco的扩展功能,一共13条,貌似很多啊!可惜有三条没介绍,不知道有啥用。
目前对我很重要的就是第6条和第13条,但在使用中我遇到了一些问题,有时间的话我会单独写文章详细记述。
-
//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
(new {UserId = 1, UserName = "user"}); - v2+
- Version column support
- IDatabase interface
- Sql Templating
- (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.