我想将集合中的所有文档作为IEnumerable返回。请帮忙!我收到一个错误:
传递到字典中的模型项的类型为'System.Threading.Tasks.Task
1[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;
}
答案 0 :(得分:2)
有两点:
GetCollection<ProductCategory>
使用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;
}
答案 1 :(得分:0)
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);
}