Use of the lightweight ORM Framework "Dapper"

Source: Internet
Author: User

What is ORM?

From the literal understanding, O is the object, the objects; R is the relation, the relation; M is the mapping, the map. So, in a nutshell, ORM is an object-relational mapping technique .

Dapper is an ORM framework under. NET.

Installation of Dapper

Installing with NuGet
Open the project in Visual Studio, click,,, and then click,,,, 工具 NuGet包管理器 管理解决方案的NuGet程序包 浏览 搜索dapper 点击搜索结果中的Dapper 勾选项目 选择安装 ;

In 解决方案管理器中点击项目 , 查看引用 if there is Dapper , the installation is successful.

Basic usage of Dapper

First, we write a person class in the model layer, and he has id,name,remark.

Also we have a person table in the database that contains the Id,name,remark three fields, where the ID is the primary key increment.

We then write a persondb class on the DAL layer that provides a basic access to the person. ConnectionString is a database connection string that is read by the configuration file.

Insert operation

Inserts an object person into the database. Insert the code text as follows. @Name means to automatically bind the name value in person.

 Public Static int Insert (person person) {     usingnew  SqlConnection (connectionString))    {         return connection. Execute ("                                     values (@Name, @Remark)"person);     }}

BULK INSERT:

/// <summary>///BULK INSERT person data, returns the number of affected rows/// </summary>/// <param name= "persons" ></param>/// <returns>affect the number of rows</returns> Public Static intInsert (list<person>persons) {    using(IDbConnection connection =NewSqlConnection (connectionString)) {        returnConnection. Execute ("INSERT into person (Name,remark) VALUES (@Name, @Remark)", persons); }}
Delete operation:
 Public Static intDelete (person person) {using(IDbConnection connection =NewSqlConnection (connectionString)) {        returnConnection. Execute ("Delete from person where [email protected]", person); }} Public Static intDelete (list<person>persons) {    using(IDbConnection connection =NewSqlConnection (connectionString)) {        returnConnection. Execute ("Delete from person where [email protected]", persons); }}
Modify the operation:
 Public Static intUpdate (person person) {using(IDbConnection connection =NewSqlConnection (connectionString)) {        returnConnection. Execute ("Update person set [email protected] where [email protected]", person); }} Public Static intUpdate (list<person>persons) {    using(IDbConnection connection =NewSqlConnection (connectionString)) {        returnConnection. Execute ("Update person set [email protected] where [email protected]", persons); }}
Query operation:
/// <summary>///query all data without a parameter/// </summary>/// <returns></returns> Public StaticList<person>Query () {using(IDbConnection connection =NewSqlConnection (connectionString)) {        returnConnection. Query<person> ("SELECT * from person").    ToList (); }}/// <summary>///querying the specified data/// </summary>/// <param name= "Person" ></param>/// <returns></returns> Public StaticPerson Query (person person) {using(IDbConnection connection =NewSqlConnection (connectionString)) {        returnConnection. Query<person> ("SELECT * from person where [email protected]", person).    Singleordefault (); }}

The in operation of the dapper complex operation query:
/// <summary>///In operation/// </summary> Public StaticList<person>Queryin () {using(IDbConnection connection =NewSqlConnection (connectionString)) {        varsql ="SELECT * from the person where ID in @ids"; //when the parameter type is array, Dappper automatically converts it        returnConnection. query<person> (SQL,New{ids =New int[2] {1,2 }, }).    ToList (); }} Public StaticList<person> Queryin (int[] IDs) {    using(IDbConnection connection =NewSqlConnection (connectionString)) {        varsql ="SELECT * from the person where ID in @ids"; //when the parameter type is array, Dappper automatically converts it        returnConnection. query<person> (SQL,New{IDs}).    ToList (); }}
Multi-statement operation

For this we introduce the following book class, which also sets the table in the database.

 Public class book{    publicintgetset;}      Public int Get Set ; }      Public string Get Set ; }}
/// <summary>///Multi-statement operation/// </summary> Public Static voidquerymultiple () {using(IDbConnection connection =NewSqlConnection (connectionString)) {        varsql ="SELECT * from person;"; varMultireader =connection.        Querymultiple (SQL); varPersonlist = multireader.read<person>(); varBooklist = multireader.read<book>();    Multireader.dispose (); }}
Join operation

We are object-oriented programming, so there are a lot of other sub-objects inside an object, and this sub-object has its own sub-object, which is the foreign key in the database representation.
For example, we have a book, it has a master Person,book is an object, the owner is an object.

 Public class bookwithperson{    publicintgetset;}      Public Get Set ; }      Public string Get Set ; }}
We naturally want a way to convert the complex foreign key relationship in the database into the object Bookwithperson we need, all the information we need is inside, and when we take the data, we just need to find the object to fetch the data, for example, the name of the owner of a book, We just need bookWithPerson.Pers.Name. If it is a one-to-many relationship we use an array, if it is many-to-many we add a layer of mapping.
Now we want to query the information of the book according to the ID of the book, including the host information.
 Public StaticBookwithperson queryjoin (book book) {using(IDbConnection connection =NewSqlConnection (connectionString)) {        varsql =@"Select B.id,b.bookname,p.id,p.name,p.remark from person as P joins book a s B on p.id = B.personid where b.id = @id;"; varresult = connection. Query<bookwithperson, person, bookwithperson>(SQL, (Bookwithperson, person)={bookwithperson.pers=Person ; returnBookwithperson;        }, book); //splitOn: "BookName");        return(Bookwithperson) result; }}
Of these, the three generic parameters of query are委托回调类型1,委托回调类型2,返回类型。 The three parameters of a formal parameter aresql语句,map委托,对象参数。 So the whole sentence means that the query is based on the SQL statement, and the person information of the query is assigned to Bookwithperson.pers, and the return Bookwithperson;book is an object parameter that provides the value of the parameter binding.
Eventually the entire method returns Bookwithperson, so all the information we need is there.



Keep Learning and growing. *** *****************************

Use of the lightweight ORM Framework "Dapper"

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.