linq2db.EntityFrameworkCore 介紹


linq2db.EntityFrameworkCore 是一個ef core的插件,對linq語法的擴展

對復雜的sql都有很好的支持,他是基於linq2db (provided by LINQ To DB)

如果你使用了linq2db的語法擴展那么你必須使用下面的方法進行查詢

 // ToLinqToDB是必須的
 var temp = qry.ToLinqToDB().ToList();

下面是 linq2db 的冰山一角

JOIN

1. InnerJoin

 var qry = from t1 in db.T
           from t2 in db.T2.InnerJoin(m => m.T1Id == t1.Id)

2.LeftJoin

 var qry = from t1 in db.T
           from t2 in db.T2.LeftJoin(m => m.T1Id == t1.Id)

3.RightJoin

 var qry = from t1 in db.T
           from t2 in db.T2.RightJoin(m => m.T1Id == t1.Id)

SUM

// 相比於原來linq,簡潔了很多。
var qry = from t1 in db.T
          from t2 in db.T2.LeftJoin(m => m.T1Id == t1.Id)
          select Sql.Ext.Sum(t1.Type == "A" ? t1.Number * (t1.SalePrice-t2.OriginalPrice) : 0).ToValue();

CountExt

//我要查t2中不重復的 t1的Id有多少個
var qry = from t1 in db.T
          from t2 in db.T2.LeftJoin(m => m.T1Id == t1.Id)
          where t1.some==''
          group new {t1,t2} by t2.some into g
          select new 
          {
              //相當於sql Count(distinct t2.T1Id)
              Number = g.CountExt(m => m.t2.T1Id, Sql.AggregateModifier.Distinct)
          }

對於一些sql函數的支持

DatePart

var qry = from t1 in db.T
                    where t1.SaleDate > beginTime 
                    group t1 by Sql.DatePart(Sql.DateParts.Month, t1 .SaleDate) into g
                    select new
                    {
                        Month = g.Key,
                        FlowAmount = g.Sum(m => m.SaleWay == "A" ? Sql.Abs(m.Number * m.SalePrice) : 0) -
                                     g.Sum(m => m.SaleWay == "B" ? Sql.Abs(m.Number * m.SalePrice) : 0)
                    };

當然還有更多的擴展方法,分別位於
包含於 Sql , Sql.Ext,AnalyticFunctions 中
linq2db文檔 : https://linq2db.github.io/index.html

當然還有批量更新的操作

如果是需要使用,那么最好再程序開始時運行以下代碼

//因為他是冪等的 ,所以可以多次運行
LinqToDBForEFTools.Initialize();

以下代碼都是從github上抄下來的。

// fast insert big recordsets
ctx.BulkCopy(new BulkCopyOptions {...}, items);

// query for retrieving products that do not have duplicates by Name
var query =
	from p in ctx.Products
	from op in ctx.Products.LeftJoin(op => op.ProductID != p.ProductID && op.Name == p.Name)
	where Sql.ToNullable(op.ProductID) == null
	select p;

// insert these records into the same or another table
query.Insert(ctx.Products.ToLinqToDBTable(), s => new Product { Name = s.Name ... });

// update these records by changing name based on previous value
query.Update(prev => new Product { Name = "U_" + prev.Name ... });

// delete records that matched by query
query.Delete();


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM