[英]MongoDB.Driver C# 2.0 Find (missing FindAll)
I want to return all documents from the collection as IEnumerable. 我想将集合中的所有文档作为IEnumerable返回。 Please help! 请帮忙! I receive an error: 我收到一个错误:
The model item passed into the dictionary is of type 'System.Threading.Tasks.Task
1[System.Collections.Generic.IEnumerable
1[Products.DataLayer.ProductCategory]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[Products.DataLayer.ProductCategory]'. 传递到字典中的模型项的类型为“ System.Threading.Tasks.Task1[System.Collections.Generic.IEnumerable
1 [Products.DataLayer.ProductCategory]]”,但是此字典需要模型项为“ System”。 Collections.Generic.IEnumerable`1 [Products.DataLayer.ProductCategory]”。
public async Task<IEnumerable<ProductCategory>> getAllCategories()
{
var client = new MongoClient("mongodb://localhost");
var database = client.GetDatabase("test");
var collection = database.GetCollection<BsonDocument>("productcategory");
var documents = collection.Find(_ => true).ToListAsync();//.ContinueWith(e=>e.Result.AsEnumerable());
documents.Wait();
var b = documents.Result.AsEnumerable();
IEnumerable<ProductCategory> ie = (IEnumerable<ProductCategory>)b;
return ie;
}
There are two points: 有两点:
GetCollection<ProductCategory>
在方法GetCollection<ProductCategory>
定义模型 Use await
instead of .Wait()
- this is not related to mongodb 使用await
代替.Wait()
-这与mongodb不相关
public async Task<IEnumerable<ProductCategory>> getAllCategories() { var client = new MongoClient("mongodb://localhost"); var database = client.GetDatabase("test"); var collection = database.GetCollection<ProductCategory>("productcategory"); var documents = await collection.Find(_ => true).ToListAsync(); return documents; }
public async Task<IEnumerable<ProductCategory>> getAllCategories()
{
var client = new MongoClient("mongodb://localhost");
var database = client.GetDatabase("test");
var collection = database.GetCollection<ProductCategory>("productcategory");
var documents = collection.Find(_ => true).ToListAsync();//.ContinueWith(e=>e.Result.AsEnumerable());
documents.Wait();
var b = documents.Result.AsEnumerable();
IEnumerable<ProductCategory> ie = (IEnumerable<ProductCategory>)b;
return ie;
}
public ActionResult Index()
{
var categoryService = new ProductCategoryService();
var categoryDetails = categoryService.getAllCategories().Result;
return View(categoryDetails);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.