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();