Skip to content

Query from Single Table

2881099 edited this page Nov 22, 2023 · 10 revisions

中文 | English

static IFreeSql fsql = new FreeSql.FreeSqlBuilder()
    .UseConnectionString(FreeSql.DataType.MySql, connectionString)
    .Build(); //Be sure to define as singleton mode

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

Single Table

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 > @val", new { val = 10 })
  .Page(1, 10)
  .ToList()
//SELECT a.`Id`, a.`Clicks`, a.`CategoryId`, a.`Title`, a.`CreateTime` 
//FROM (select * from Topic where clicks > @val) a 

When WithSql is used multiple times, it will be converted to UNION ALL query

v3.2.666 UnionAll QueryWithTempQuery + FromQuery Nested Query

v3.2.666 WithMemory Query using memory data

If the cross server or data table is cached

var list = new List<Topic>();
list.Add(new Topic { ... });
list.Add(new Topic { ... });

fsql.Select<Topic>()
  .WithMemory(list)
  .ToList()
//SELECT a.`Id`, a.`Clicks`, a.`CategoryId`, a.`Title`, a.`CreateTime` 
//FROM (
//  SELECT ...
//  UNION ALL
//  SELECT ...
//) a 

Reference

Clone this wiki locally