博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
NPoco学习篇(2):NPoco简介
阅读量:5058 次
发布时间:2019-06-12

本文共 6580 字,大约阅读时间需要 21 分钟。

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

  1. 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进行操作。
  2. 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.
  3. 继续。。。
    //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);

     

  4. 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");

     

  5. 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条,但在使用中我遇到了一些问题,有时间的话我会单独写文章详细记述。

  1. //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"});
  2. v2+
  3. Version column support
  4. IDatabase interface
  5. Sql Templating
  6. (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.

 

转载于:https://www.cnblogs.com/dusdong/p/ORM_NPoco.html

你可能感兴趣的文章
【POJ1845】Sumdiv(数论/约数和定理/等比数列二分求和)
查看>>
在WPF中使用Caliburn.Micro搭建MEF插件化开发框架
查看>>
IdentityServer4-用EF配置Client(一)
查看>>
UWP: 掌握编译型绑定 x:Bind
查看>>
asp.net core系列 35 EF保存数据(2) -- EF系列结束
查看>>
WPF程序加入3D模型
查看>>
WPF中实现多选ComboBox控件
查看>>
读构建之法第四章第十七章有感
查看>>
C#中的IEnumerable<T>知识点
查看>>
android访问链接时候报java.net.MalformedURLException: Protocol not found
查看>>
dwz ie10一直提示数据加载中
查看>>
Windows Phone开发(4):框架和页 转:http://blog.csdn.net/tcjiaan/article/details/7263146
查看>>
Windows Phone Marketplace 发布软件全攻略
查看>>
Unity3D研究院之打开Activity与调用JAVA代码传递参数(十八)【转】
查看>>
语义web基础知识学习
查看>>
hexo个人博客添加宠物/鼠标点击效果/博客管理
查看>>
python asyncio 异步实现mongodb数据转xls文件
查看>>
关于WPF的2000件事 02--WPF界面是如何渲染的?
查看>>
单元测试、、、
查看>>
深入理解include预编译原理
查看>>