`FirstOrDefaultAsync().ContinueWith()` 与 `Select().FirstOrDefaultAsync()` 之间的区别

huangapple go评论53阅读模式
英文:

Difference between FirstOrDefaultAsync().ContinueWith() and Select().FirstOfDefaultAsync()

问题

这两段代码有什么不同?我了解第一段代码将使数据库请求执行转换,而第二段代码将在请求完成后进行转换计算。

await _dbContext.myEntity.Select(x => x.ToModel()).FirstOrDefaultAsync();

await _dbContext.myEntity.FirstOrDefaultAsync().ContinueWith(x => x?.Result?.ToModel());

其中 .ToModel() 是一个扩展方法,用于将数据库对象转换为领域对象并处理空值。

英文:

What is the difference between these 2 snippets of code? As I understand the first one is going to make the database request do the transformation and the second is going to compute the transformation once the request is done?

> await _dbContext.myEntity.Select(x=> x.ToModel()).FirstOrDefaultAsync();

and

> await _dbContext.myEntity.FirstOrDefaultAsync().ContinueWith(x=> x?.Result?.ToModel())

Where .ToModel() is an extension method that transform database objects to domain objects and handle null values.

答案1

得分: 3

除非您已经向EF(Entity Framework)解释了如何将自定义方法ToModel翻译成SQL,否则两者之间唯一的区别将是第二个使用了ContinueWith,这在现代.NET中被不鼓励。假设您正在使用EF Core的后续迭代之一,它可以在最终投影中处理自定义函数(通过获取myEntity的所有数据,因此如果不是所有数据实际上都需要用于ToModel,可能会导致过度获取)。

英文:

> As I understand the first one is going to make the database request do the transformation and the second is going to compute the transformation once the request is done?

Unless you have explained EF how to translate your custom method ToModel into SQL the only difference between the two would be that the second one uses ContinueWith which is discouraged (click, click) in modern .NET in "general" case. Assuming you are using one of the later iterations of EF Core - it can handle custom function in the final projection (by fetching all the data for the myEntity, so it can lead to over-fetching if not all data is actually needed for ToModel).

huangapple
  • 本文由 发表于 2023年2月6日 21:34:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75361987.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定