当前位置:网站首页>A gift for dapper users

A gift for dapper users

2020-12-07 08:39:16 nicye

Written in the beginning

as everyone knows Dapper yes .NET The lightest and fastest ORM, It likes to write SQL The gospel of Manon , be relative to SqlHelper It's more convenient , According to statistics 10 individual .NETer Yes 9 individual Used to Dapper.

because .NET The special environment , Yes Lambda Love of expression trees , So there are a lot of things on the market based on Dapper Lightweight of ORM, Almost all of them have in common , Give Way Dapper Support Lambda Expression tree , Writing is as smooth as running water .

Today, we introduce a powerful ORM, He offers a more hidden API function , Use and Dapper It's no different .

understand Lambda Expression tree

This is from Lambda The expression begins with , One of the words is missing “ Trees ” word , There is a big difference .

expression , The following grammar sugar operation , Produced IL As like as two peas :

// Use C# 2.0 Get string length by anonymous method in 
Func<string, int> strLength = delegate(string str) { return str.Length; };
Console.WriteLine(strLength("Hello World!"));

// Use Lambda expression 
//( List of explicit type parameters )=> { sentence },lambda The longest version of an expression 
strLength = (string str) => { return str.Length; };
Console.WriteLine(strLength("Hello World!"));

// A single expression as the body 
//( List of explicit type parameters )=>  expression 
strLength = (string str) => str.Length;
Console.WriteLine(strLength("Hello World!"));

// Parameter list of implicit type 
//( Implicit type parameter list )=>  expression 
strLength = (str) => str.Length;
Console.WriteLine(strLength("Hello World!"));

// Quick syntax for a single parameter 
// Parameter name  =>  expression 
strLength = str => str.Length;
Console.WriteLine(strLength("Hello World!"));

And the expression tree , The code is written like an expression , as follows :

Expression<Func<string, int>> strLength = str => str.Length;

Expression trees do not support code blocks ( Curly braces )

Try to write simply , We usually write like this , Although it's almost the same as expression code , But the return value is not the same as the expression , One more generic Expression<>.

Expression tree is also called expression tree , Represent the code in an abstract way as an object tree , Each node in the tree itself is an expression . Expression trees are not executable code , It's a data structure . It is the code that converts the code written into a tree structure during compilation , In order to carry out reverse analysis .

Above :(strLength.Body as MemberExpression).Member.Name You can get the value "Length"

Because the expression tree can be parsed reversely , In the past ten years EF It's always been the leader , Every year, China has to produce several ORM, Most of them are based on expression tree parsing .

Expression tree parsing

.NET Technical articles never lack articles like expression tree parsing , Interested can baidu search , Numerous , But it's not easy to be perfect .

FreeSql We have done a lot of work on the expression tree analysis , give an example :

1、 Sub table in Inquire about

.Where(a => fsql.Select<T>().ToList(b => b.Id).Contains(a.Id))
//WHERE a.Id in (select id from t)

2、 Sub table exists Inquire about

.Where(a => fsql.Select<T>().Any(b => b.Id == a.Id))
//WHERE exists(select 1 from t where Id = a.Id)

3、 Date formatting

ToList(a => a.CreateTime.ToString("HH:mm:ss"))
//date_format(a.`CreateTime`, '%H:%i:%s')

4、 Open the window function

ToList(a => SqlExt.Rank().Over().OrderBy(a.Id).OrderByDescending(b.EdiId).ToValue())
//rank() over(order by a.Id, b.EdiId desc)

5、Join Sub table

ToList(a => string.Join(",", fsql.Select<StringJoin01>().ToList(b => b.Id)))
//(SELECT group_concat(b.`Id` separator ',') FROM `StringJoin01` b) 

These features are in different databases , We need to do the corresponding adaptation ,FreeSql It also supports expression tree parsing of navigation attributes , I just want to prove that it's not easy to be meticulous .

Instead of making trouble for yourself , It's better to use it directly ?

Ado.Net Extended implementation

Instead of making trouble for yourself , It's better to use it directly ?FreeSql Provides a non - staple API Usage habits , Use it to follow Dapper No difference .

Support MySql/SqlServer/PostgreSQL/Oracle/Sqlite/Firebird/ Reach a dream / Supernatural power / Renmin Jincang / Hangao /MsAccess More than ten database adaptations , And support .NetFramework 4.0 platform 、.NET5.0、.NET Core2.1 + platform .

First step : To database SqlServer For example, visit , All you need to do is install the divided package :

dotnet add packages FreeSql.Provider.SqlServer

or

Install-Package FreeSql.Provider.SqlServer

The second step : Create entity class

class TestConnectionExt {
    public Guid id { get; set; }
    public string title { get; set; }
    public DateTime createTime { get; set; } = DateTime.Now;
}

The third step : Start CRUD

using (var conn = new SqlConnection(connectString)) {
    var list = conn.Select<TestConnectionExt>().Where(a => a.id == item.id).ToList();
}

using (var conn = new SqlConnection(connectString)) {
    var item = new TestConnectionExt { title = "testinsert" };
    var affrows = conn.Insert(item).ExecuteAffrows();
}

using (var conn = new SqlConnection(connectString)) {
    var affrows = conn.Update<TestConnectionExt>()
        .Where(a => a.Id == xxx)
        .Set(a => a.title, "testupdated")
        .ExecuteAffrows();
}

using (var conn = new SqlConnection(connectString)) {
    var affrows = conn.Delete<TestConnectionExt>()
        .Where(a => a.Id == xxx)
        .ExecuteAffrows();
}

Add or update :

using (var conn = new SqlConnection(connectString)) {
    var affrows = conn.InsertOrUpdate<TestConnectionExt>()
        .SetSource(item)
        .ExecuteAffrows();
}

Add above 、 Delete 、 modify 、 Inquire about , Entity class operations are already supported , And support batch insert 、 Batch update 、 Batch deletion 、 Multi-table query 、 Navigation property query .

You can enjoy FreeSql Almost all functions .

reflection : Use this API It seems that you can easily access to abp vnext in ?

Conclusion

FreeSql Use the world's most relaxed open source protocol MIT Trusteeship in github:https://github.com/dotnetcore/FreeSql A stable version with two years of high frequency iterations has been released v2.0, Welcome to follow and use .

Support .NetFramework 4.0+、.NetCore 2.1+、Xamarin Other support NetStandard All operating platforms .

Support MySql/SqlServer/PostgreSQL/Oracle/Sqlite/Firebird/ Reach a dream / Supernatural power / Renmin Jincang / Hangao /MsAccess database .

QQ Group :4336577( Is full )、8578575( On-line )、52508226( On-line )

版权声明
本文为[nicye]所创,转载请带上原文链接,感谢
https://chowdera.com/2020/12/202012070838169077.html