EF 10 LeftJoin & RightJoin 的支持

360影视 欧美动漫 2025-03-23 09:41 4

摘要:我们前面介绍 Linq LeftJoin/RightJoin 的时候提到过 EF Core 也会支持 LeftJoin/RightJoin,EF Core 在 preview 1 的时候支持了 LeftJoin 在 preview 2 中支持了 RightJo

Intro

我们前面介绍 Linq LeftJoin/RightJoin 的时候提到过 EF Core 也会支持 LeftJoin/RightJoin,EF Core 在 preview 1 的时候支持了 LeftJoin 在 preview 2 中支持了 RightJoin,现在 preview 2 已经发布我们一起来看下吧

Sample

测试示例如下:

publicstaticasyncTaskEFLeftRightJoinSample
{
varservices =newServiceCollection;
services.AddSQLite("Data Source=test.db", optionsAction: options =>
{
options.LogTo(Console.WriteLine);
});
awaitusingvarserviceProvider = services.BuildServiceProvider;

usingvarscope = serviceProvider.CreateScope;
vardbContext = scope.ServiceProvider.GetRequiredService;
awaitdbContext.Database.EnsureDeletedAsync;
awaitdbContext.Database.EnsureCreatedAsync;

dbContext.Jobs.Add(newJob { Id =1, Name ="test"});
dbContext.Employees.Add(newEmployee { Id =1, JobId =1, Name ="Alice"});
newEmployee { Id =2, JobId =2, Name ="Jane"});
awaitdbContext.SaveChangesAsync;

varresult =awaitdbContext.Employees.AsNoTracking
// ReSharper disable once EntityFramework.UnsupportedServerSideFunctionCall
.LeftJoin(dbContext.Jobs.AsNoTracking, e => e.JobId, j => j.Id, (e, j) =>new
{
e.Id,
e.Name,
e.JobId,
JobName = j == ?"Unknown": j.Name
})
.ToArrayAsync;
foreach(variteminresult)
{
Console.WriteLine(JsonSerializer.Serialize(item));
}

result =awaitdbContext.Jobs.AsNoTracking

.RightJoin(dbContext.Employees.AsNoTracking, j => j.Id, e => e.JobId, (j, e) =>new
{
e.Id,
e.Name,
e.JobId,
JobName = j == ?"Unknown": j.Name
})
.ToArrayAsync;
foreach(variteminresult)
{

}
}

为了方便看测试结果我们将 Log 输出到 Console 里方便打印实际数据库的查询是否符合预期

LeftJoinRightJoin

从上面执行的 SQL 可以看得出来我们的 LeftJoin & RightJoin 被正确翻译成了 SQL

大家留意代码的话会发现有一行注释

// ReSharper disable once EntityFramework.UnsupportedServerSideFunctionCall

这行注释是给 ReSharper 和 Rider 的,不加的话目前会有一个 warning,示例如下:

在之前的版本里不能转成 SQL 但从 EF Core 10 开始就可以了,ReSharper 后续应该会有所改进避免对 LeftJoin/RightJoin 产生 warning 吧

References

https://github.com/WeihanLi/SamplesInPractice/blob/main/net10sample/Net10Samples/LinqSamples.cs#L74

来源:opendotnet

相关推荐