一点前言: 我正在 EF Core 6 中工作,并尝试使用 Fluent API 创建 SQL 查询。我想要实现的原始 SQL 查询是:
SELECT *
FROM [table] AS [t]
LEFT JOIN [table0] AS [t0] ON [t].[field1] = [t0].[field1]
LEFT JOIN [table1] AS [t1] ON [t].[field2] = [t1].[field2] AND [t1].[field3] = [t0].[field3]
LEFT JOIN [table2] AS [t2] ON [t1].[field4] = [t2].[field4]
WHERE ([t0].[field5] = GUID)
我在 EF Core 中有以下内容:
var query = db.Table
.Include((e) => e.Table0Navigation)
.Include((e) => e.Table1Navigation)
.Include((e) => e.Table1Navigation.Table2Navigation)
.Where((e) => e.Table0Navigation.GUID == request.GUID)
这是模式的模型(删除了无关字段)
表:
[Key]
public int field0 { get; set; }
[ForeignKey("field1")]
public int field1 { get; set; }
[ForeignKey("field2")]
public string field2 { get; set; } = null!;
public Table1? Table1Navigation { get; set; }
public Table0 Table0Navigation { get; set; } = null!;
表0:
[Key]
public int field1 { get; set; }
public int? field3 { get; set; }
public GUID field5 { get; set; }
表1:
public int field3 { get; set; }
public string field2 { get; set; } = null!;
public int? field4 { get; set; }
public Table2 Table2Navigation { get; set; } = null!;
表2:
public int field4 { get; set; }
我为Table 1的实体定义的上下文中的关系/模型是:
entity.HasKey((e) => new { e.field2 });
entity
.HasMany((e) => e.TableNavigation) //Navigation from Table 1 to Table
.WithOne((e) => e.Table1Navigation) //Navigation from Table to Table 1
.HasForeignKey((e) => e.field2) //Represents Table
.HasPrincipalKey((e) => e.field2) //Represents Table 1
.IsRequired(false); //Needed for LEFT JOIN
entity
.HasMany((e) => e.Table0Navigation) //Represents navigation from Table 1 to Table 0
.WithOne((e) => e.Table1Navigation) //Represents navigation from Table 0 to Table 1
.HasForeignKey((e) => e.field1) //Represents Table 0
.HasPrincipalKey((e) => e.field1) //Represents Table 1
.IsRequired(false); //Needed for LEFT JOIN
其他表没有在模型中定义关系定义。
重要的是要注意,Table可能有一个带有值的
field2
,但Table 1没有包含field2
的相应记录,但结果仍然应该返回,只是正常的值从 表 1 中的记录得到的结果是 NULL
field3
来自 Table 0 (t0),位于 Table (t) 和 Table 1 (t1) 之间的联接
我面临的问题是,我永远无法让它在这两种条件下进行连接,它可以在
field2
上正确执行此操作,但我永远无法让它在 field3
上执行此操作
我已经尝试了几乎所有方法,但仍然无法弄清楚,也许你可以提供帮助?
提前谢谢您。
我使用 EFCore 7,但这也应该适用于 6。
var id = Guid.NewGuid();
var data = ctx.Tables
.Where((e) => e.Table0Navigation.field5 == id)
.Select(e => new {
e.field0,
e.Table0Navigation.field1,
e.Table1Navigation.field2,
e.Table1Navigation.Table2Navigation.field4})
.ToArray();
我收到一个询问
SELECT [t].[field0], [t0].[field1], [t1].[field2], [t2].[field4]
FROM [Tables] AS [t]
INNER JOIN [Table0] AS [t0] ON [t].[Table0Navigationfield1] = [t0].[field1]
LEFT JOIN [Table1] AS [t1] ON [t].[Table1Navigationfield3] = [t1].[field3]
LEFT JOIN [Table2] AS [t2] ON [t1].[Table2Navigationfield4] = [t2].[field4]
WHERE [t0].[field5] = @__id_0
根据需要向
Select
添加更多列。