简体   繁体   English

从2.0 MongoDb c#驱动程序获取结果

[英]Getting results from 2.0 MongoDb c# driver

I have built up a sample app using both the 1.0 and 2.0 c# drivers for MongoDb. 我已经使用1.02.0 c#驱动程序为MongoDb构建了一个示例应用程序。

They serialize the same objects and I'm able to write with both and read from the 1.0. 它们序列化相同的对象,我可以用两者写入并从1.0读取。 But I'm not able to use FindAsync in the 2.0 to give me any results. 但是我无法在2.0中使用FindAsync给我任何结果。

Here is my 1.0 query that returns one document: 这是我的1.0查询,它返回一个文档:

var results = collection.AsQueryable<FlatCatalogItem>()
                        .FirstOrDefault(c => c.BatchId == "2015.01.27" 
                                            && c.Upcs.Any(u => u.UPC == "123456803"));

My 2.0 query using the same data with the FindAsync looks like this: 使用与FindAsync相同的数据的我的2.0查询如下所示:

var task = collection.FindAsync(item => item.BatchId == "2015.01.27" 
                                     && item.Upcs.Any(u => u.UPC == "123456803"));
task.Wait();
var results = task.Result;

The AsyncCursor that is returned from result has nothing in it. 从结果返回的AsyncCursor中没有任何内容。

results.MoveNextAsync().Wait(); // results.Current.Count = 0

This could be my ignorance with async and await, or perhaps I've missed something else with the 2.0 find methods? 这可能是我对异步和等待的无知,或者我可能错过了2.0查找方法的其他东西? Note that I do not want to use the legacy 2.0 drivers 请注意,我不想使用旧版2.0驱动程序

The new API is async -only, you shouldn't block on it. 新的API是async - 你不应该阻止它。 It's not scalable and could possibly lead to deadlocks. 它不可扩展,可能导致死锁。 Use async-await all the way or keep using the old API. 使用async-await一直或继续使用旧的API。 In an async method the query should look like this: async方法中,查询应如下所示:

async Task Foo()
{
    FlatCatalogItem first = await collection.
        Find(c => c.BatchId == "2015.01.27" && c.Upcs.Any(u => u.UPC == "123456803")).
        FirstOrDefaultAsync();

    // use first
}

Can you please try this? 你能试试吗?

var task = collection.Find(item => item.BatchId == "2015.01.27" 
                                     && item.Upcs.Any(u => u.UPC == "123456803")).FirstOrDefaultAsync();

task.Wait();
var results = task.Result;

I trying to get used to the new API as well. 我也试图习惯新的API。

Or perhaps a little more elegant: 或者更优雅一点:

var result = collection.Find(item => item.BatchId == "2015.01.27" 
                                  && item.Upcs.Any(u => u.UPC == "123456803"))
                       .FirstOrDefaultAsync().Result;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM