1. 程式人生 > >.Net輕量級ORM-NPoco的使用方法

.Net輕量級ORM-NPoco的使用方法

文章引用自NPoco官方Wiki,地址:https://github.com/schotime/NPoco/wiki,因公司網路不穩定,有時無法訪問,特將其摘抄。

Home

Adam Schroder edited this page on 1 Jul 2016 · 49 revisions

Welcome to the NPoco wiki! NPoco is a fork of PetaPoco with a handful of extra features.

Getting Started: Your first query

  1. publicclassUser
  2. {
  3. public
    intUserId{get;set;}
  4. publicstringEmail{get;set;}
  5. }
  6. using(IDatabase db =newDatabase("connStringName"))
  7. {
  8. List<User> users = db.Fetch<User>("select userId, email from users");
  9. }

Note: Database needs to be disposed to close the connection (think of it as your connection object).

This works by mapping the column names to the property names on the User

 object. This is a case-insensitive match.
There is no mapping setup needed for this (query only) scenario.

Available on NuGet: 
Also checkout the JabbR room if you have a question. Here are the release notes.

Mapping

Adam Schroder edited this page on 21 Apr 2016 · 10 revisions

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.

Basic mapping is done via attributes. The most used ones are:

  1. [TableName] This takes a "name" parameter which indicates the table for which the Poco class will be mapped to.

  2. [PrimaryKey] This has a "columnName" parameter which takes the column name of the primary key for the table. Multiple primary keys can be specified by separating the columns with a comma. There is also an "autoIncrement" property which is used to indicate whether the primary key column is auto incremented e.g. identity column in Sql Server. By default this is true. For Oracle there is also a "sequenceName" property which will be used when inserting data with Oracle.

  3. [Column] This is used if the column name does not match the property name.

  4. [Ignore] This property will be ignored and cannot be mapped to.

  5. [ResultColumn] Properties marked with the Result column can be mapped into, however these 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.

  6. [ComputedColumn] Properties with the Computed column attribute work the same way as the Result column attributes however they will be auto selected in the SQL.

  7. [SerializedColumn] (v3+ only) Properties with the Serialized column attribute will serialize their data with the default serializer unless changed by implementing a IColumnSerializer. There is a NPoco.JsonNet library which allows you to use the JsonNetColumnSerializer. These are configured once by:

  1. DatabaseFactory.ColumnSerializer=newJsonNetColumnSerializer();

Example

  1. [TableName("Users")]
  2. [PrimaryKey("UserId")]
  3. publicclassUser
  4. {
  5. publicintUserId{get;set;}
  6. [Column("emailAddress")]
  7. publicstringEmail{get;set;}
  8. [ResultColumn]
  9. publicstringExtraInfo{get;set;}
  10. [Ignore]
  11. publicintTemp{get;set;}
  12. }

If you don't like attribute based mapping, the take a look at fluent / convention based mapping

Query Single Object

schotime edited this page on 27 Apr 2012 · 3 revisions

Selecting an object from the database can be done in a few different ways.

By Id

The easiest way to load an object from the database is by passing the primary key to the SingleById<T>() method.

  1. IDatabase db =newDatabase("connStringName");
  2. User u = db.SingleById<User>(3);

Via SQL

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.

  1. User u = db.Single<User>("where emailaddress = @0","[email protected]");
  2. or
  3. User u = db.Single<User>("select u.* from users u where emailaddress = @0","[email protected]");

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

Ryan Gates edited this page on 28 Jun 2016 · 5 revisions

This wiki page refers to the User class found here.

Inserting a new record

  1. IDatabase db =newDatabase("connStringName");
  2. User u =newUser()
  3. {
  4. Email="[email protected]",
  5. LastLoggedIn=DateTime.UtcNow
  6. };
  7. db.Insert(u);

This will insert the User object into the users table generating a new identity value. This value will be populated back into the object after the insert statement. For example, the following would be true.

Reading the new record

  1. var user = db.SingleById(u.UserId);
  2. 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.

  1. var user = db.SingleById(1);
  2. user.Email="[email protected]";
  3. 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.

  1. var user = db.SingleById(1);
  2. db.Delete(user);

or

  1. db.Delete<User>(1);

Upsert the record

This will insert a record if it is new or update an existing record if it already exists. Its existence is determined by its primary key.

  1. IDatabase db =newDatabase("connStringName");
  2. User u =newUser()
  3. {
  4. Email="[email protected]",
  5. LastLoggedIn=DateTime.UtcNow
  6. };
  7. db.Save(u);

Query List

schotime edited this page on 27 Apr 2012 · 1 revision

Here are some of the ways to fetch multiple rows from the database.

Eager

1: Fetch all

  1. List<User> users = db.Fetch<User>();

2: Fetch with criteria

  1. List<User> users = db.Fetch<User>("where isActive = 1");

3: Fetch with raw SQL

  1. List<User> users = db.Fetch<User>("select u.* from users where u.isActive = 1");

Lazy

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.

  1. List<User> users = db.Query<User>("select u.* from users where u.isActive = 1");

Query Paging

schotime edited this page on 23 Mar 2013 · 3 revisions

There are two main methods used for paging.

Page<T>

  1. IDatabase db =newDatabase("connStringName");
  2. Page<T> pagedUsers = db.Page<User>(2,10,"select u.* from users u order by userid");

where Page<T> is defined by:

  1. publicclassPage<T>
  2. {
  3. publiclongCurrentPage{get;set;}
  4. publiclongTotalPages{get;set;}
  5. publiclongTotalItems{get;set;}
  6. publiclongItemsPerPage{get;set;}
  7. publicList<T>Items{get;set;}
  8. }

Note: 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.

The first parameter to the Page<T> method is the page number. This number begins at 1 for the first page. The second parameter is the size of the page. In the example above, the second page with 10 users in it will be returned.

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:

            
           

相關推薦

.Net輕量級ORM-NPoco的使用方法

文章引用自NPoco官方Wiki,地址:https://github.com/schotime/NPoco/wiki,因公司網路不穩定,有時無法訪問,特將其摘抄。 Home Adam Schroder edited this page on 1 Jul 201

.NET輕量級ORM組件Dapper葵花寶典

C# .NET Dapper ORM ADO.NET 一、摘要為什麽取名叫《葵花寶典》?從行走江湖的世界角度來講您可以理解為一本"武功秘籍",站在我們IT編程的世界角度應該叫"開發寶典"。如果您在工作中主要接觸的是操作MySQL數據庫,但您又想學習和

.NET輕量級ORM框架Dapper入門精通

orm dapper dapper for sql serv dapper for mysql ef 一、課程介紹本次分享課程包含兩個部分《.NET輕量級ORM框架Dapper修煉手冊》和《.NET輕量級ORM框架Dapper葵花寶典》,阿笨將帶領大家一起領略輕量級ORM框架Dapper的

.NET 輕量級 ORM 框架 - Dapper 介紹

轉自:https://blog.csdn.net/hanjun0612/article/details/52170204 Dapper簡單介紹: Dapper is a single file you can drop in to your project that will exte

.net輕量級ORM -- PetaPoco/NPOCO框架使用說明

list select 1年 刪除 record spa def app 不能 .net的輕量級ORM -- PetaPoco/NPOCO框架使用說明(具體參看:http://www.toptensoftware.com/petapoco/)   從11年就開始嘗試使用輕量

【從零開始搭建自己的.NET Core Api框架】(三)集成輕量級ORM——SqlSugar:3.3 自動生成實體類

i++ 點運算 自己的 yui content project style ref 數據庫表 系列目錄 一. 創建項目並集成swagger   1.1 創建   1.2 完善 二. 搭建項目整體架構 三. 集成輕量級ORM框架——SqlSugar   3.1 搭建環境  

從壹開始前後端分離【 .NET Core2.0 +Vue2.0 】框架之七 || API專案整體搭建 6.2 輕量級ORM

更新 1、在使用的時候,特別是 update 的時候,如果不知道哪裡有問題,記得檢視資料庫 和 實體類 的欄位,是否大小寫一致,比如 name 和 Name 要學會使用資料庫監控分析器 程式碼已上傳Github+Gitee,文末有地址   書接上文:《從壹開始前後端分離【 .NET

core學習歷程三 從壹開始前後端分離【 .NET Core2.0 +Vue2.0 】框架之六 || API專案整體搭建 6.1 倉儲模式 從壹開始前後端分離【 .NET Core2.0 +Vue2.0 】框架之七 || API專案整體搭建 6.2 輕量級ORM

繼續學習 “老張的哲學”博主的系列教程 從壹開始前後端分離【 .NET Core2.0 +Vue2.0 】框架之六 || API專案整體搭建 6.1 倉儲模式   教程這章只是簡單地過了一遍倉儲層、業務邏輯層、應用層,沒遇到大問題 ==============================

【ADO.NET基礎】加密方法經典集合

char 自定義 rst reac stream algorithm array temp esc 各種加密方法集錦: using System; using System.Security.Cryptography; using System.Text; using S

asp.net 網站開發常用方法

.sh sql 進行 構造 file rep ria output sender 生成驗證碼: using System; using System.Data; using System.Configuration; using System.Collections

ASP.NET操作DataTable各種方法

[] ret 增加 另一個 turn 根據 好的 asp.net 默認 轉:http://www.cnblogs.com/isking/p/6178268.html http://www.cnblogs.com/sntetwt/p/3496477.html public

基於輕量級ORM框架Dapper的擴展說明

sca mapper server proxy mage alt .exe () 數據庫 這裏簡單的介紹一下本人基於Dapper作的一些簡單的擴展,供大家參考。 為何要使用這款框架,相信大家看到下面排名就清楚了 其實在各大網站上,我們大概都會看到這樣的一個對比效果圖

.net文件下載方法匯總

urn headers smi sed lag origin 手冊 length bytes /TransmitFile實現下載 protected void Button1_Click1(object sender, EventArgs e)

.NET輕量級DBHelpers數據訪問組件

本地 framework 安裝 easy dbconnect 手冊 方法 path gem 一、摘要 一說到ADO.NET大家可能立刻想到的就是增、刪、改、查(CRUD)操作,然後再接就想到項目中的SQLHelper。沒錯本課分享課阿笨給大家帶來的是來源於github

asp.net 下載帶壓縮方法

.com file net arp com test https 壓縮 tar SharpZipTest.zip: https://njc127.ctfile.com/fs/15754707-226563396[url=https://njc127.ctfile.com/f

.net mvc控制器傳遞方法到視圖

測試 mode ring 一個 傳遞 代碼 mvc控制器 cap del 很多人都是在視圖裏面定義方法,然後再使用。我個人也是這麽幹的。但是為了驗證是否可以將方法從控制器傳遞到視圖,所以做了個測試。結果真的可以。原理是利用了委托(delegate),因為委托本身就是一種類型

ASP.NET獲取路徑的方法

end cdir mappath 加載 sam main RR tex b站 HttpContext.Current.Request.PhysicalPath; // 獲得當前頁面的完整物理路徑.比如 F:\XFU.NSQS\project\website\Defau

asp.net 按鈕執行前後臺方法——前臺彈出提示信息,確認後繼續執行後臺方法,取消則不執行後臺方法

一個 inf ret font AD itl 博客 www. asp.net 我們做一個測試的web頁面,只需要一個button+一個label就ok啦,通過button按鈕的後臺事件修改label的text屬性值來測試是否執行了後臺事件裏的代碼 前臺 寫一個js方法:

查看Windows電腦上.NET Framework版本的方法(找了好久的方法

nbsp image blank 命令提示符 framework microsoft 我們 tps 16px 照網上大多數人的方法,在路徑 C:\Windows\Microsoft.NET\Framework 下可以查看到.NET Framework的版本,不過無論Win7

使用基本的Dapper,好用的輕量級Orm框架

字符 字段 ger ram response 存儲過程 help sea ora public class DBHelper<T>where T:class { /// <summary> /// 數據庫連接字符串