c# linq ef 多表查询写法
时间: 2023-10-18 18:46:11 浏览: 154
在C#中使用LINQ和Entity Framework进行多表查询的写法可以有多种方式,以下是一些常见的示例:
1. 基本查询:
```csharp
var query = from t1 in dbContext.Table1
join t2 in dbContext.Table2 on t1.Id equals t2.Table1Id
select new { t1, t2 };
```
2. 过滤条件查询:
```csharp
var query = from t1 in dbContext.Table1
join t2 in dbContext.Table2 on t1.Id equals t2.Table1Id
where t1.Name == "someName" && t2.IsActive
select new { t1, t2 };
```
3. 多个连接查询:
```csharp
var query = from t1 in dbContext.Table1
join t2 in dbContext.Table2 on t1.Id equals t2.Table1Id
join t3 in dbContext.Table3 on new { t1.Id, t2.Id } equals new { t3.Table1Id, t3.Table2Id }
select new { t1, t2, t3 };
```
4. 左连接查询:
```csharp
var query = from t1 in dbContext.Table1
join t2 in dbContext.Table2 on t1.Id equals t2.Table1Id into joinedTable
from subTable in joinedTable.DefaultIfEmpty()
select new { t1, subTable };
```
以上只是一些常见的多表查询写法示例,实际应用中可以根据具体需求进行灵活组合和扩展。
阅读全文