简体   繁体   中英

MongoDB.Driver C# 2.0 Find (missing FindAll)

I want to return all documents from the collection as 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]'.

 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:

  1. Define model in method GetCollection<ProductCategory>
  2. Use await instead of .Wait() - this is not related to 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);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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