FreeSql (十五)查詢數據


FreeSql在查詢數據下足了功能,鏈式查詢語法、多表查詢、表達式函數支持得非常到位。

static IFreeSql fsql = new FreeSql.FreeSqlBuilder()
    .UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=10")
    .Build(); //請務必定義成 Singleton 單例模式

class Topic {
    [Column(IsIdentity = true)]
    public int Id { get; set; }
    public string Title { get; set; }
    public int Clicks { get; set; }
    public DateTime CreateTime { get; set; }

    public int CategoryId { get; set; }
}

查詢數據

fsql.Select<Topic>()
  .Where(a => a.Id == 10)
  .ToList();
///SELECT a.`Id`, a.`Clicks`, a.`CategoryId`, a.`Title`, a.`CreateTime` 
//FROM `Topic` a 
//WHERE (a.`Id` = 10)

fsql.Select<Topic>()
  .Where(a => a.Id == 10 && a.Id > 10 || a.Clicks > 100)
  .ToList();
///SELECT a.`Id`, a.`Clicks`, a.`CategoryId`, a.`Title`, a.`CreateTime` 
//FROM `Topic` a 
//WHERE (a.`Id` = 10 AND a.`Id` > 10 OR a.`Clicks` > 100)

fsql.Select<Topic>()
  .Where(a => new []{1,2,3}.Contains(a.Id))
  .ToList();
//SELECT a.`Id`, a.`Clicks`, a.`CategoryId`, a.`Title`, a.`CreateTime` 
//FROM `Topic` a 
//WHERE (a.`Id` in (1,2,3))

WithSql

fsql.Select<Topic>()
  .WithSql("select * from Topic where clicks > 10")
  .Page(1, 10)
  .ToList()
//SELECT a.`Id`, a.`Clicks`, a.`CategoryId`, a.`Title`, a.`CreateTime` 
//FROM (select * from Topic where clicks > 10) a 

WithSql 使用多次為 UNION ALL 查詢

WhereDynamicFilter

ISelect.WhereDynamicFilter 方法實現動態過濾條件(與前端交互),支持的操作符:

  • Contains/StartsWith/EndsWith/NotContains/NotStartsWith/NotEndsWith:包含/不包含,like '%xx%',或者 like 'xx%',或者 like '%xx'
  • Equal/NotEqual:等於/不等於
  • GreaterThan/GreaterThanOrEqual:大於/大於等於
  • LessThan/LessThanOrEqual:小於/小於等於
  • Range:范圍查詢
  • DateRange:日期范圍,有特殊處理 value[1] + 1
  • Any/NotAny:是否符合 value 中任何一項(直白的說是 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"" : ""Eq"",
      ""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%')

API

方法 返回值 參數 描述
ToSql string 返回即將執行的SQL語句
ToList List 執行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
Any bool 執行SQL查詢,是否有記錄
Sum T Lambda 指定一個列求和
Min T Lambda 指定一個列求最小值
Max T Lambda 指定一個列求最大值
Avg T Lambda 指定一個列求平均值
【分頁】
Count long 查詢的記錄數量
Count <this> out long 查詢的記錄數量,以參數out形式返回
Skip <this> int offset 查詢向后偏移行數
Offset <this> int offset 查詢向后偏移行數
Limit <this> int limit 查詢多少條數據
Take <this> int limit 查詢多少條數據
Page <this> int pageIndex, int pageSize 分頁
【條件】
Where <this> Lambda 支持多表查詢表達式
WhereIf <this> bool, Lambda 支持多表查詢表達式
Where <this> string, parms 原生sql語法條件,Where("id = ?id", new { id = 1 })
WhereIf <this> bool, string, parms 原生sql語法條件,WhereIf(true, "id = ?id", new { id = 1 })
WhereCascade <this> Lambda 實現多表查詢時,向每個表中附加條件
【分組】
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 })
Disdinct <this> .Distinct().ToList(x => x.GroupName) 是對指定字段
【排序】
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 })
【聯表】
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個表
【其他】
As <this> string alias = "a" 指定別名
Master <this> 指定從主庫查詢(默認查詢從庫)
WithTransaction <this> DbTransaction 設置事務對象
WithConnection <this> DbConnection 設置連接對象

系列文章導航


免責聲明!

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



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