英文:
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
).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论