Trace Dapper.NET Source Code - The important concept of dynamic create method "code from result" optimizes efficiency
Wei
Posted on December 7, 2020
Github Link : Trace-Dapper.NET-Source-Code
6. Strongly Typed Mapping Part3: The important concept of dynamic create method "code from result" optimizes efficiency
Then use Expression to solve the Reflection version problem, mainly using Expression features: 「Methods can be dynamically created during Runtime」
to solve the problem.
Before this, we need to have an important concept: 「Reverse the most concise code from the result」
optimizing efficiency. For example: In the past, a classic topic of "printing regular triangle stars'' when learning a program to make a regular triangle of length 3, the common practice would be loop + recursion the way
void Main ()
{
Print(3,0);
}
static void Print(int length, int spaceLength)
{
if (length < 0)
return;
else
Print(length - 1, spaceLength + 1);
for (int i = 0; i < spaceLength; i++)
Console.Write(" ");
for (int i = 0; i < length; i++)
Console.Write("* ");
Console.WriteLine("");
}
But in fact, this topic can be changed to the following code when the length is already known
Console.WriteLine(" * ");
Console.WriteLine(" * * ");
Console.WriteLine("* * * ");
This concept is very important, because the code is reversed from the result, so the logic is straightforward and efficient
, and Dapper uses this concept to dynamically build methods.
Example:
The Name property of User Class corresponds to Reader Index 0, the type is String, and the default value is null
The Age attribute of User Class corresponds to Reader Index 1, the type is int, and the default value is 0
void Main ()
{
using (var cn = Connection)
{
var result = cn.Query<User>("select N'Wei' Name,26 Age").First();
}
}
class User
{
public string Name { get; set; }
public int Age { get; set; }
}
If the system can help generate the following logical methods, then the efficiency will be the best
User dynamic method ( IDataReader reader )
{
var user = new User();
var value = reader[0];
if( !(value is System.DBNull) )
user.Name = (string)value;
value = reader[1];
if( !(value is System.DBNull) )
user.Age = (int)value;
return user;
}
In addition, the above example can be seen for Dapper SQL Select corresponds to the Class attribute order is very important
, so the algorithm of Dapper in the cache will be explained later, which is specifically optimized for this.
Posted on December 7, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.