Skip to content

Query Data

AlexLEWIS edited this page Aug 20, 2021 · 18 revisions

中文 | English

FreeSql has made great efforts in querying data, especially the functions such as chain query syntax, multi-table query, expression function, etc.

Special introduction to WhereDynamicFilter

The ISelect.WhereDynamicFilter method implements dynamic filter conditions (interacting with the front-end), supported operators:

  • Contains/StartsWith/EndsWith/NotContains/NotStartsWith/NotEndsWith: include/not include, like'%xx%', or like'xx%', or like'%xx'
  • Equal/NotEqual
  • GreaterThan/GreaterThanOrEqual
  • LessThan/LessThanOrEqual
  • Range: Range query
  • DateRange: date range, with special processing value[1] + 1
  • Any/NotAny: Does it match any item in value (to put it bluntly, SQL IN)
DynamicFilterInfo dyfilter = JsonConvert.DeserializeObject<DynamicFilterInfo>(@"
{
  ""Logic"" : ""Or"",
  ""Filters"" :
  [
    {
      ""Field"" : ""Code"", ""Operator"" : ""NotContains"", ""Value"" : ""val1"", 
      ""Filters"" : [{ ""Field"" : ""Name"", ""Operator"" : ""NotStartsWith"", ""Value"" : ""val2"" }]
    },
    {
      ""Field"" : ""Parent.Code"", ""Operator"" : ""Equals"", ""Value"" : ""val11"",
      ""Filters"" : [{ ""Field"" : ""Parent.Name"", ""Operator"" : ""Contains"", ""Value"" : ""val22"" }]
    }
  ]
}");
fsql.Select<VM_District_Parent>().WhereDynamicFilter(dyfilter).ToList();
//SELECT a.""Code"", a.""Name"", a.""ParentCode"", a__Parent.""Code"" as4, a__Parent.""Name"" as5, a__Parent.""ParentCode"" as6 
//FROM ""D_District"" a 
//LEFT JOIN ""D_District"" a__Parent ON a__Parent.""Code"" = a.""ParentCode"" 
//WHERE (not((a.""Code"") LIKE '%val1%') AND not((a.""Name"") LIKE 'val2%') OR a__Parent.""Code"" = 'val11' AND (a__Parent.""Name"") LIKE '%val22%')

Dynamic sorting: ISelect.OrderByPropertyName("Parent.Code")

API

Methods Return Parameters Description
ToSql string Return the SQL statement to be executed
ToList List<T1> 执行SQL查询,返回 T1 实体所有字段的记录,若存在导航属性则一起查询返回,记录不存在时返回 Count 为 0 的列表
ToList<T> List<T> Lambda 执行SQL查询,返回指定字段的记录,记录不存在时返回 Count 为 0 的列表
ToList<T> List<T> string field 执行SQL查询,返回 field 指定字段的记录,并以元组或基础类型(int,string,long)接收,记录不存在时返回 Count 为 0 的列表
ToOne T1 执行SQL查询,返回 T1 实体所有字段的第一条记录,记录不存在时返回 null
ToAggregate<T> List<T> Lambda 执行SQL查询,返回指定字段的聚合结果(适合不需要 GroupBy 的场景)
Any bool Execute SQL query, if there are records, return true, otherwise return false.
Sum T Lambda Specify a column and calculate the sum.
Min T Lambda Specify a column and calculate the minimum value.
Max T Lambda Specify a column and calculate the maximum value.
Avg T Lambda Specify a column, calculate the average value.
【Pagination】
Count long The number of queried records
Count <this> out long The number of queried records, returned in the form of parameter out
Skip <this> int offset Query the number of rows shifted backward
Offset <this> int offset Query the number of rows shifted backward
Limit <this> int limit Query a specified amount of data
Take <this> int limit Query a specified amount of data
Page <this> int pageIndex, int pageSize Pagination
【Where】
Where <this> Lambda Supports multi-table query expressions, multiple use is equivalent to AND.
WhereIf <this> bool, Lambda Support multi-table query expression
Where <this> string, parms Native Sql syntax conditions, Where("id = @id", new {id = 1 }) Note that the prefix @ will be determined according to the specific database
WhereIf <this> bool, string, parms Native Sql syntax conditions, WhereIf(true, "id = @id", new {id = 1 }) Note that the prefix @ will be determined according to the specific database
WhereCascade <this> Lambda When querying multiple tables, add conditions to each table.
WhereDynamicFilter <this> DynamicFilterInfo Dynamic filter conditions (interact with the front end)
【Group】
GroupBy <this> Lambda 按选择的列分组,GroupBy(a => a.Name)
GroupBy <this> string, parms 按原生sql语法分组,GroupBy("concat(name, @cc)", new { cc = 1 }) ,注意前缀@,根据具体数据库决定
Having <this> string, parms 按原生sql语法聚合条件过滤,Having("count(name) = @cc", new { cc = 1 }),注意前缀@,根据具体数据库决定
Distinct <this> .Distinct().ToList(x => x.GroupName) 是对指定字段
【Order】
OrderBy <this> Lambda 按列排序,OrderBy(a => a.Time),可多次使用
OrderByDescending <this> Lambda 按列倒向排序,OrderByDescending(a => a.Time)
OrderBy <this> string, parms 按原生sql语法排序,OrderBy("count(name) + @cc", new { cc = 1 })
OrderByPropertyName string, bool 按属性名字符串排序(支持导航属性)
【Join】
LeftJoin <this> Lambda 左联查询,可使用导航属性,或指定关联的实体类型
InnerJoin <this> Lambda 联接查询,可使用导航属性,或指定关联的实体类型
RightJoin <this> Lambda 右联查询,可使用导航属性,或指定关联的实体类型
LeftJoin <this> string, parms 左联查询,使用原生sql语法,LeftJoin("type b on b.id = a.id and b.clicks > @clicks", new { clicks = 1 })
InnerJoin <this> string, parms 联接查询,使用原生sql语法,InnerJoin("type b on b.id = a.id and b.clicks > @clicks", new { clicks = 1 })
RightJoin <this> string, parms 右联查询,使用原生sql语法,RightJoin("type b on b.id = a.id and b.clicks > @clicks", new { clicks = 1 })
From <this> Lambda 多表查询,3个表以上使用非常方便,目前设计最大支持10个表
【Other】
As <this> string alias = "a" 指定别名
Master <this> 指定从主库查询(默认查询从库)
CommandTimeout <this> int 命令超时设置(秒)
WithTransaction <this> DbTransaction 设置事务对象
WithConnection <this> DbConnection 设置连接对象
WithLock <this> Enum SqlServer NoLock 等特有的设置
ForUpdate <this> bool 排他更新锁,对不同的数据库已作适配,详细说明见注释
AsQueryable IQueryable 将 ISelect 转换为 IQueryable,此方法主要用于扩展,比如:abp IRepository GetAll() 接口方法需要返回 IQueryable 对象。注意:IQueryable 方法污染较为严重,请尽量避免此转换
InsertInto int string, Lambda 将查询转换为 INSERT INTO tableName SELECT ... FROM t 执行插入
ToUpdate IUpdate<TENtity> 将查询转为更新对象
ToDelete IDelete<TENtity> 将查询转为删除对象
ToTreeList List<TEntity> 将父子关系的数据以 TreeList 的形式返回
AsTreeCte ISelect (up, pathSelector, level) 递归查询父子关系表
Clone this wiki locally