The related discussion about Dapper.net

Source: Internet
Author: User
Tags emit

When you are young, why not fight for your dreams once? Even if badly beaten, also do not regret to have that young frivolous. Feeling a lot, recently things also a lot, blog also rarely updated, after all, everyone needs to work for their own lives.

Recently encountered a person in a group said, here no longer repeat, probably means that they are proficient in all kinds of understanding, interview all kinds of hanging, I sincerely asked him, ask him if he understand the underlying principle of these things, whether to understand the underlying source code, can modify the source according to the actual situation, who knows he spit trough said loaded forced , say that so much knowledge can not see the source code and understand the principle of it. But I just want to say, this is your own mastery, is not proficient in the framework should not understand the source code and principles? Is mastery just knowing how to use it simply? Am I talking in a wrong way?

Recently, there is a problem, that is, some questions about Dapper.net, why is the efficiency of dapper.net high? What is the operating principle of this component? To tell the truth, I looked for a long time did not find similar articles, do not know is not my search method is not right, but also hope to find similar good Article friends sent me to see, knowledge is to share, do not skimp on your knowledge, let us progress together.

Here is a brief introduction to its principle

I. Dapper.net Overview:

Project development, we need to consider the project's technical architecture, especially the database at the bottom of the more considerations. Now for the database access has ado.net,ef,dapper.net, and so on, different circumstances will have different choices, when the discussion will say "xx is very good, xx efficiency is very high" and so on, in short, we have to do a meeting. (Most of the time, before the meeting of the project to choose what technology has been decided, but do not open a meeting will appear to work not rigorous ... In the selection of dapper.net, some people said dapper.net efficiency, very good, do not know that the new person said a "Why dapper.net high efficiency?" ”

So embarrassed ...

Dapper.net is a simple orm that is designed to quickly generate objects from SQL query results. Dapper.net supports the execution of SQL queries and maps their results to a strongly typed list or a dynamic object list. dapper.net caches information for each query. This comprehensive cache helps generate objects from approximately twice times the LINQ-to-SQL query. The current cache is handled by two concurrentdictionary objects , which are never purged.

The dapper.net adds two mapping functions to the IDbConnection interface through an extension method, which two function are named executemapperquery. the first mapping result is a strongly typed list, and the second mapping result is a list of dynamic objects. executemappercommand executes and does not return a result set. All three methods accept parameters as anonymous classes, where property values are mapped to SQL parameters with the same name.

The dapper.net is designed to handle only result sets to object mappings. It does not handle the relationship between objects, and it does not automatically generate any type of SQL query.

Two. Dapper.net Principle Analysis:

Through the dapper.net source we can find that it is mainly through the "partial method and partial class" for extensible design, there is a "partial method and partial class" knowledge can see this blog: http://www.cnblogs.com/pengze0902/p/6369541.html. Dapper.net also assumes that the connection is open and ready, dapper.net by extending the IDbConnection interface. After the dapper.net connection to the database is complete, you can do something about it, and then we'll look at how these operations are implemented.

1.Query () method:

Query<t> (Thisstringobjectnull
NULL BOOL true int NULL NULL

The change method represents the execution of the query and returns the data entered by T. The method is a generic method of the query () method, has 7 parameters, the first parameter is the IDbConnection extension class, represents the extension of the IDbConnection interface, which uses optional parameters to improve the extensibility of the method. In the implementation of the Query method, there is a commanddefinition class that represents the key aspects of the SQL operation. There is a Getinit () method under this class.

2.GetInit () method:

We all know that dapper.net can quickly get and produce objects by emit a sequence queue that reflects IDataReader. The Getinit () method is a static method in which the "Type CommandType" parameter of the method represents a connection to the Command object and returns a action<idbcommand> delegate.

Let's take a look at how the IDataReader sequence queue is reflected through emit.

if  out  return  action;}

Link<tkey, tvalue> is a generic distribution class, which is a micro-cache to see if there is a action<idbcommand> delegate.

var " Bindbyname " typeof (bool)); var " initiallongfetchsize " typeof (int));

The above two operations primarily get bindbyname and Initiallongfetchsize get basic property settings.

if(Bindbyname! =NULL|| Initiallongfetchsize! =NULL)            {                varMETHOD =NewDynamicMethod (Commandtype.name +"_init",NULL,NewType[] {typeof(IDbCommand)}); varIl =method.                GetILGenerator (); if(Bindbyname! =NULL)                {IL.                    Emit (OPCODES.LDARG_0); Il.                    Emit (Opcodes.castclass, CommandType); Il.                    Emit (Opcodes.ldc_i4_1); Il. Emitcall (Opcodes.callvirt, Bindbyname,NULL); }                if(Initiallongfetchsize! =NULL)                {IL.                    Emit (OPCODES.LDARG_0); Il.                    Emit (Opcodes.castclass, CommandType); Il.                    Emit (OPCODES.LDC_I4_M1); Il. Emitcall (Opcodes.callvirt, Initiallongfetchsize,NULL); } il.                Emit (Opcodes.ret); Action= (action<idbcommand>) method. CreateDelegate (typeof(action<idbcommand>)); }

This step is a core part of the operation, taking advantage of the emit reflection operation. Based on the basic property setting of the corresponding name obtained in the previous step, the DynamicMethod object is used to define and represent a dynamic method that can be compiled, executed, and discarded. The discarded method can be used for garbage collection. Calls the object's GetILGenerator method, which returns the method's Microsoft intermediate language (MSIL) generator, which has a default MSIL stream size of 64 bytes. After determining that the base property setting is not empty, call the Emit method of the ILGenerator class, Emit () places the specified instruction on the instruction stream, which receives an IL stream. Emitcall () places the call or callvirt instruction in the Microsoft Intermediate language (MSIL) stream to invoke the varargs method. We see the Opcodes class, which describes intermediate language (IL) directives. CreateDelegate () completes the dynamic method and creates a delegate that can be used to execute it.

Once the object is built with the above reflection, the corresponding database operation is then performed.

3.QueryImpl ():

 Private StaticIenumerable<t> queryimpl<t> ( Thisidbconnection CNN, commanddefinition Command, Type effectivetype) {            Objectparam =command.            Parameters; varIdentity =NewIdentity (Command.commandtext, Command.commandtype, CNN, effectivetype, param = =NULL?NULL: Param. GetType (),NULL); varinfo =getcacheinfo (Identity, param, command.            Addtocache); IDbCommand cmd=NULL; IDataReader Reader=NULL; BOOLWasclosed = CNN. state = =connectionstate.closed; Try{cmd=command. SetupCommand (CNN, info.)                Paramreader); if(wasclosed) CNN.                Open (); Reader= cmd. ExecuteReader (wasclosed? CommandBehavior.CloseConnection |CommandBehavior.SequentialAccess:CommandBehavior.SequentialAccess); Wasclosed=false; vartuple =info.                Deserializer; inthash =Getcolumnhash (reader); if(Tuple. Func = =NULL|| Tuple. Hash! =hash) {                    if(Reader. FieldCount = =0)                         yield  Break; Tuple= info. Deserializer =NewDeserializerstate (hash, Getdeserializer (Effectivetype, Reader,0, -1,false)); if(command.)                Addtocache) Setquerycache (identity, info); }                varFunc =tuple.                Func; varConverttotype = Nullable.getunderlyingtype (effectivetype)??Effectivetype;  while(reader. Read ()) {Objectval =func (reader); if(val = =NULL|| Val isT) {yield return(T) Val; }                    Else                    {                        yield return(T) Convert.changetype (Val, Converttotype, CultureInfo.InvariantCulture); }                }                 while(reader. NextResult ()) {} reader.                Dispose (); Reader=NULL; Command.            OnCompleted (); }            finally            {                if(Reader! =NULL)                {                    if(!reader. IsClosed)Try{cmd. Cancel (); }                        Catch{/*don ' t spoil the existing exception*/} reader.                Dispose (); }                if(wasclosed) CNN.                Close (); if(cmd! =NULL) cmd.            Dispose (); }        }

This method is the core method for executing the query operation, after the related operation of the Commanddefinition class is obtained, the corresponding object is taken. This method is an extension method of IDbConnection, commanddefinition represents the related operand of SQL, and type represents a valid type passed in. The Identity object represents the identity of the cached query in dapper, which is a partial class that can be scaled accordingly. Getcacheinfo () gets the cache information.

Three. dapper.net extension:

This part is Jiehuaxianfo, this part of the code is a dapper.net code to do a package, can be similar to the way to operate other ORM, the need to pick up, do not go around to find these things.

Dapper.net Extension Method Package

Dapper Bag

Four. Summary:

This blog post is I have to bite the bullet to write, because there is no similar article, even reference to the data are not, the most is the call code demo, for the principle and the underlying source code parsing basically no, here on this blog to lead the Great God to its comprehensive analysis. I hope to have a little help to everyone, but also as much as possible.

Related to Dapper.net

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.