sqlsugar多表联查
时间: 2023-08-31 17:12:44 浏览: 113
SQLSugar的多表联查可以使用Join和JoinTable两种方式实现。
1. 使用Join方法
Join方法可以将多个表按照指定条件进行联查,示例代码如下:
```c#
var list = db.Queryable<Student>()
.Join<School>((s, c) => s.SchoolId == c.Id)
.Join<Grade>((s, c) => s.GradeId == c.Id)
.Select<Student, School, Grade>((s, c, d) => new
{
StudentName = s.Name,
SchoolName = c.Name,
GradeName = d.Name
})
.ToList();
```
上面的代码将Student、School、Grade三个表联查,按照SchoolId和GradeId进行关联,最后选择Student、School、Grade表中的部分字段,并将结果保存在一个匿名类型对象中。
2. 使用JoinTable方法
JoinTable方法可以将多个表按照指定条件进行关联,并将结果保存在一个新的实体类中,示例代码如下:
```c#
var list = db.Queryable<Student>()
.JoinTable<School, Grade>((s, c, d) => s.SchoolId == c.Id && s.GradeId == d.Id)
.Select<Student, School, Grade>((s, c, d) => new StudentViewModel
{
StudentName = s.Name,
SchoolName = c.Name,
GradeName = d.Name
})
.ToList();
```
上面的代码将Student、School、Grade三个表联查,按照SchoolId和GradeId进行关联,并将结果保存在一个新的StudentViewModel实体类中。最后选择Student、School、Grade表中的部分字段,并将结果保存在StudentViewModel对象中。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)