. NET's lightweight ORM-Petapoco/npoco Framework usage notes

Source: Internet
Author: User

. NET's lightweight ORM-Petapoco/npoco Framework usage notes
(See: http://www.toptensoftware.com/petapoco/)

Since 11, the use of lightweight Orm:petapoco has been attempted, and the following are basic usage methods. In addition Npoco is Petapoco upgrade version, is another person maintenance, the original Petapoco basically no longer maintenance. Npoco most usages are consistent with Petapoco, with some additional features. Npoco I'll consider writing an article about it.

Run a query

First define Poco
Note: Poco means that plain old CLR object refers generally to simple. NET classes with a parameterless constructor only get set:

//represents a record in the "Articles" table Public classarticle{ Public Longarticle_id {Get;Set; }  Public stringTitle {Get;Set; }  PublicDateTime date_created {Get;Set; }  Public BOOLDraft {Get;Set; }  Public stringContent {Get;Set; }}

Inquire

//Create A Petapoco database objectvardb=NewPetapoco.database ("connectionStringName");//Show all articlesforeach(varAinchDb. Query<article> ("SELECT * from articles") {Console.WriteLine ("{0}-{1}", a.article_id, a.title);}

Note: Database has fetch and query two methods

Fetch returns LIST<T>.
The query returns by yield return so that no traversal of the record is done by reprinting the entire data into memory.

Note: A small amount of data is more convenient to fetch, a lot of data and just one-way traversal or return please use Query to save memory.

Returns a single value

Long count=db. executescalar<Long> ("Select Count (*) from articles");

Return a single record

var a = db. Singleordefault<article> ("select * from articles WHERE [email protected]"123 ));

Note: Error when running Singleordefault returns more than 1 records

Paging Query

Note: All big data volumes are queried using this paging method, and the Petapoco paging query is the database paging.

var result=db. Page<article> (1//  <--page number and items per page"  SELECT * from Articles WHERE [e-mail protected] ORDER by date_posted DESC""coolstuff  ");

will return

 Public classPage<t>whereT:New() { Public Longcurrentpage {Get;Set; }  Public LongItemsPerPage {Get;Set; }  Public LongTotalPages {Get;Set; }  Public LongTotalItems {Get;Set; }  PublicList<t> Items {Get;Set; }}

Run the paging method, in fact Petapoco will do two things:

Returns the total number of records that are matched.
Gets the number of word records needed for the page.

Note: Petapoco will convert your SQL Component page SQL, so there is a certain limit to SQL, please do not use SELECT * and write SQL strictly separated by spaces, to avoid PETAPOCO cannot parse your SQL correctly.

Add, update, delete records
New

//Create the articlevarA=Newarticle (); A.title="My new Article"; A.content="Petapoco is here"; a.date_created=Datetime.utcnow;//Insert ItDb. Insert ("Articles","article_id", a);//By now A.ARTICLE_ID would have the ID of the new article

Update

//Get a recordvarA=db. Singleordefault<article> ("SELECT * from articles WHERE [email protected]",123);//Change ItA.content="Petapoco was here again";//Save ItDb. Update ("Articles","article_id", a); can be updated with anonymous objects, the following is an example db that updates the title only. Update ("Articles","article_id",New{title="New title"},123);

Decorate your Poco

//represents a record in the "Articles" table[Petapoco.tablename ("Articles")][petapoco.primarykey ("article_id")] Public classarticle{ Public Longarticle_id {Get;Set; } Public stringTitle {Get;Set; } PublicDateTime date_created {Get;Set; } Public BOOLDraft {Get;Set; } Public stringContent {Get;Set; }}

This makes it easier to operate

//Insert a recordvarA=Newarticle (); A.title="My new Article"; A.content="Petapoco is here"; a.date_created=datetime.utcnow;db. Insert (a);//Update ItA.content="blah blah";d B. Update (a);//Delete ItDb. Delete (a);

Of course, you can run it.

// Delete an articledb. Delete<article> ("WHERE [email protected]"123); // Update an articledb. Update<article> ("SET [email protected] WHERE [email protected]"" New Title " 123);

Some properties can also be ignored

 Public class article{    [Petapoco.ignore]    publiclong  somecalculatedfieldperhaps    {          Get Set ;     }}    

Using transactions

using (var trans =Db.gettransaction ()) {    // do transacted updates    here  //  Commit    trans.complete ();}

SQL Builder

varId=123;varSql=PetaPoco.Sql.Builder. Append ("SELECT * from articles")    . Append ("WHERE [email protected]", id);if(start_date. HasValue) SQL. Append ("and Date_created>[email protected]", start_date. Value);if(end_date. HasValue) SQL. Append ("and Date_created<[email protected]", end_date. Value);varA=db. query<article> (SQL);

You can also use a name:

Sql. Append ("andDate_created>[email protected] and Date_created<[email protected]"  ,     new     {         start=datetime.utcnow.adddays (-2),         end= Datetime.utcnow     };);        

You can also use this

var sql=PetaPoco.Sql.Builder ()    . Select ("*")    . From ("articles")    . Where ("date_created < @0", Datetime.utcnow)    . ("date_created DESC");

. NET's lightweight ORM-Petapoco/npoco Framework usage notes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.