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; }

<span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> CategoryId { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

}

查询数据

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

方法返回值参数描述
ToSqlstring返回即将执行的SQL语句
ToListList执行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 的列表
ToOneT1执行SQL查询,返回 T1 实体所有字段的第一条记录,记录不存在时返回 null
Anybool执行SQL查询,是否有记录
SumTLambda指定一个列求和
MinTLambda指定一个列求最小值
MaxTLambda指定一个列求最大值
AvgTLambda指定一个列求平均值
【分页】
Countlong查询的记录数量
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设置连接对象

系列文章导航

标签: FreeSql, ORM, CodeFirst
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
FreeSql中,多表查询可以通过链式查询语法来实现。例如,如果要进行一对多的查询,可以使用以下代码: ```csharp var result = fsql.Select<Tag>() .Where(a => a.Tags.AsSelect().Any(t => t.Parent.Id == 10)) .ToList(); ``` 这个查询会返回所有满足条件的Tag对象。其中,`a.Tags.AsSelect()`表示对Tags属性进行子查询,`Any(t => t.Parent.Id == 10)`表示在子查询中筛选出Parent.Id等于10的记录。\[2\] 如果要进行多对多的查询,可以使用以下代码: ```csharp var result = fsql.Select<Song>() .Where(s => s.Tags.AsSelect().Any(t => t.Name == "国语")) .ToList(); ``` 这个查询会返回所有满足条件的Song对象。其中,`s.Tags.AsSelect()`表示对Tags属性进行子查询,`Any(t => t.Name == "国语")`表示在子查询中筛选出Name等于"国语"的记录。\[3\] 通过这种方式,你可以方便地进行多表查询操作。 #### 引用[.reference_title] - *1* [FreeSql十五查询数据](https://blog.csdn.net/yonghuairuogu/article/details/106858498)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [FreeSql查询功能介绍](https://blog.csdn.net/weixin_30278237/article/details/99613942)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值