MongoDB.Driver C#2.0查找(缺少FindAll)

时间:2015-06-02 10:52:07

标签: c# mongodb

我想将集合中的所有文档作为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;
    }

2 个答案:

答案 0 :(得分:2)

有两点:

  1. 在方法GetCollection<ProductCategory>
  2. 中定义模型
  3. 使用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);
    }