C#-FirstOrDefaultAsync()和SingleOrDefaultAsync()与FindAsync()EFCore
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C#-FirstOrDefaultAsync()和SingleOrDefaultAsync()与FindAsync()EFCore,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2040字,纯文字阅读大概需要3分钟。
内容图文
我们有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()的值.
解决方法:
FindAsync
In much of the scaffolded code, FindAsync can be used in place of
FirstOrDefaultAsync.
SingleOrDefaultAsync
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.
内容总结
以上是互联网集市为您收集整理的C#-FirstOrDefaultAsync()和SingleOrDefaultAsync()与FindAsync()EFCore全部内容,希望文章能够帮你解决C#-FirstOrDefaultAsync()和SingleOrDefaultAsync()与FindAsync()EFCore所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。