在C#中从mongodb获取单个对象 [英] Getting a single object from mongodb in C#

查看:185
本文介绍了在C#中从mongodb获取单个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我选择了一段使用MongoDB驱动程序的代码,像这样从集合中获取单个对象……这可能不对,对吗?不能.这是正确的吗?是的,这是正确的吗?是的.............................................................................................将大劲......................................................................................................................................................有没有更好的方法来获得这个?

I've picked up a piece of code that is using the MongoDB driver like this to get a single object from a collection...this can't be right, can it? Is there a better way of getting this?

IMongoCollection<ApplicationUser> userCollection;
....
userCollection.FindAsync(x => x.Id == inputId).Result.ToListAsync().Result.Single();

推荐答案

是的.

首先不使用FindAsync,而是使用Find.在IFindFluent结果上,使用SingleAsync扩展方法,并在异步方法中等待返回的任务:

First of all don't use FindAsync, use Find instead. On the IFindFluent result use the SingleAsync extension method and await the returned task inside an async method:

async Task MainAsync()
{
    IMongoCollection<ApplicationUser> userCollection = ...;

    var applicationUser = await userCollection.Find(_ => _.Id == inputId).SingleAsync();
}

新驱动程序专门使用async-await.不要使用Task.Result阻止它.

The new driver uses async-await exclusively. Don't block on it by using Task.Result.

这篇关于在C#中从mongodb获取单个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆