[英]Getting a single object from mongodb in C#
我找到了一段代码,它使用这样的 MongoDB 驱动程序从集合中获取单个对象......这不可能是对的,是吗? 有没有更好的方法来获得这个?
IMongoCollection<ApplicationUser> userCollection;
....
userCollection.FindAsync(x => x.Id == inputId).Result.ToListAsync().Result.Single();
就在这里。
首先不要使用FindAsync
,而是使用Find
。 在IFindFluent
结果上,使用SingleAsync
扩展方法并在异步方法中等待返回的任务:
async Task MainAsync()
{
IMongoCollection<ApplicationUser> userCollection = ...;
var applicationUser = await userCollection.Find(_ => _.Id == inputId).SingleAsync();
}
新驱动程序专门使用 async-await。 不要使用Task.Result
阻止它。
您应该在执行之前限制您的查询,否则您将首先找到所有结果,然后只读取其中一个。
您可以在FindAsync
使用FindOptions
指定限制,或者在执行查询之前使用流畅的语法来限制查询:
var results = await userCollection.Find(x => x.Id == inputId).Limit(1).ToListAsync();
ApplicationUser singleResult = results.FirstOrDefault();
ToListAsync
的结果将是一个列表,但由于您将结果数量限制为 1,该列表将只有一个您可以使用 Linq 访问的结果。
在较新版本的 MongoDB Find() 中已弃用,因此您可以使用
collection.FindSync(o => o.Id == myId).Single()
或者
collection.FindAsync(o => o.Id == myId).Result.Single()
您还可以使用SingleOrDefault()
,如果未找到匹配项,则返回 null 而不是抛出异常。
我无法获得方法:
coll.Find(_ => _.Id == inputId).SingleAsync();
在我收到错误时工作
InvalidOperationException: Sequence contains more than one element c#
所以我最终使用了.FirstOrDefault()
例子:
public FooClass GetFirstFooDocument(string templatename)
{
var coll = db.GetCollection<FooClass>("foo");
FooClass foo = coll.Find(_ => _.TemplateName == templatename).FirstOrDefault();
return foo;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.