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; }
public Category Category { get; set; }
}
class Category {
[Column(IsIdentity = true)]
public int Id { get; set; }
public string Name { get; set; }
public int ParentId { get; set; }
public CategoryType Parent { get; set; }
public List<Topic> Topics { get; set; }
}
class CategoryType {
public int Id { get; set; }
public string Name { get; set; }
}
1、导航属性联表
fsql.Select<Topic>()
.LeftJoin(a => a.Category.Id == a.CategoryId)
.LeftJoin(a => a.Category.Parent.Id == a.Category.ParentId)
.ToList();
//SELECT a.`Id`, a.`Title`, a.`Clicks`, a.`CreateTime`, a.`CategoryId`, a__Category.`Id` as6, a__Category.`Name`, a__Category.`ParentId`
//FROM `Topic` a
//LEFT JOIN `Category` a__Category ON a__Category.`Id` = a.`CategoryId`
//LEFT JOIN `CategoryType` a__Category__Parent ON a__Category__Parent.`Id` = a__Category.`ParentId`
提示:正确配置导航关系后,不再需要手工调用 LeftJoin
2、复杂联表
fsql.Select<Topic, Category, CategoryType>()
.LeftJoin((a,b,c) => a.CategoryId == b.Id)
.LeftJoin((a,b,c) => b.ParentId == c.Id)
.ToList();
//或者
fsql.Select<Topic>().From<Category, CategoryType>((s, b, c) => s
.LeftJoin(a => a.CategoryId == b.Id)
.LeftJoin(a => b.ParentId == c.Id))
.ToList();
//SELECT a.`Id`, a.`Title`, a.`Clicks`, a.`CreateTime`, a.`CategoryId`, b.`Id` as6, b.`Name`, b.`ParentId`
//FROM `Topic` a
//LEFT JOIN `Category` b ON a.`CategoryId` = b.`Id`
//LEFT JOIN `CategoryType` c ON b.`ParentId` = c.`Id`
3、SQL联表
fsql.Select<Topic>()
.LeftJoin("Category b on b.Id = a.CategoryId and b.Name = ?bname", new { bname = "xxx" })
.ToList();
//SELECT a.`Id`, a.`Title`, a.`Clicks`, a.`CreateTime`, a.`CategoryId`
//FROM `Topic` a
//LEFT JOIN Category b on b.Id = a.CategoryId and b.Name = ?bname
延申问题:SQL联表如何 b 表的字段如果在 ToList 中指定?
.ToList(a => new
{
bid = Convert.ToInt32("b.Id"),
bName = "b.Name"
})
系列文章导航
-
(十七)联表查询
参考资料
| 《新人学习指引》 | 《Select》 | 《Update》 | 《Insert》 | 《Delete》 | |
| 《表达式函数》 | 《CodeFirst》 | 《DbFirst》 | 《BaseEntity》 | |
| 《Repository》 | 《UnitOfWork》 | 《过滤器》 | 《乐观锁》 | 《DbContext》 | |
| 《读写分离》 | 《分区分表》 | 《租户》 | 《AOP》 | 《黑科技》 | 更新日志 |