c# - FirstOrDefaultAsync() & SingleOrDefaultAsync() 与 FindAsync() EFCore

标签 c# linq ef-core-2.0

我们有 3 种不同的方法从 EFCore 获取单个项目,它们是 FirstOrDefaultAsync()SingleOrDefaultAsync()(包括没有返回默认值的版本,我们也有FindAsync() 可能还有更多类似 LastOrDefaultAsync() 的目的。

var findItem = await dbContext.TodoItems
    .FindAsync(request.Id)
    .ConfigureAwait(false);

var firstItem = await dbContext.TodoItems
    .FirstOrDefaultAsync(i => i.Id == request.Id)
    .ConfigureAwait(false);

var singleItem = await dbContext.TodoItems
    .SingleOrDefaultAsync(i => i.Id == request.Id)
    .ConfigureAwait(false);

我想知道它们之间的区别。到目前为止我所知道的是我们 FirstOrDefaultAsync() 得到第一个给定的条件,(通常使用这个因为我们知道不止一个项目可以满足条件),另一方面我们使用SingleOrDefaultAsync() 因为我们知道只能找到一个可能的匹配项,而 FindAsync() 可以在给定主键的情况下获取项目。

我认为 FirstOrDefaultAsync() & SingleOrDefaultAsync() 总是命中数据库(对此不确定),而 FindAsync() 这是Microsoft 文档中的内容:

Asynchronously finds an entity with the given primary key values. If an entity with the given primary key values exists in the context, then it is returned immediately without making a request to the store. Otherwise, a request is made to the store for an entity with the given primary key values and this entity, if found, is attached to the context and returned. If no entity is found in the context or the store, then null is returned.

所以我的问题是,如果我们用于 FirstOrDefault()SingleOrDefault()FindAsync() 的给定条件是主键, 我们有什么实际区别吗?

我的想法是,第一次使用它们时总是会触发数据库,​​但是接下来的调用呢?。可能 EFCore 可以使用与 FindAsync() 相同的上下文来获取 FirstOrDefault()SingleOrDefault() 的值,< strong>也许?。

最佳答案

查找异步

In much of the scaffolded code, FindAsync can be used in place of FirstOrDefaultAsync.

单一或默认异步

fetches more data and does unnecessary work. throws an exception if there's more than one entity that fits the filter part.

FirstOrDefaultAsync

doesn't throw if there's more than one entity that fits the filter part.

https://learn.microsoft.com/en-us/aspnet/core/data/ef-rp/crud?view=aspnetcore-2.2#singleordefaultasync-vs-firstordefaultasync

关于c# - FirstOrDefaultAsync() & SingleOrDefaultAsync() 与 FindAsync() EFCore,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54819705/

相关文章:

c# - 需要在 C# 中显式抛出异常吗?

c# - 找出 linq 完成了多少次迭代

c# - Entity Framework Core 在转换时是延迟加载

c# - 实体核心 2.0.3 异常 : must be reducible node

c# - 如何在DataGridView中搜索没有数据库的文件

c# - 为什么我的堆上有两个空的 ThreadAbortExceptions?

c# - 如何在 OxyPlot 图表上绘制多个 LineSeries?

c# - LINQ 考虑通过 double 比较元素

c# - 无法将 null 分配给类型数组的匿名属性

c# - 复合主键部分的 EF 一对多