Search code examples
asp.net-mvc-5mongodb-.net-driver

CsharpDriver 2.2.3 Findasync never return


I want to list all of documents in my datas and using Findasync (csharpdriver 2.2.3) to find all but it never returns. Could you give me some advices. Here is my codes

public class HomeController : Controller
    {
        readonly MyVietnamContext Context = new MyVietnamContext();
        private List<UserModels> list = new List<UserModels>();
        public ActionResult Index()
        {
            GetUsers().Wait();
            return View(list);
        }

        public async Task GetUsers()
        {
            var filter = new BsonDocument();
            var collection = Context.Collection();            
            var cursor = await collection.FindAsync(filter);
            while (await cursor.MoveNextAsync())
            {
                var batch = cursor.Current;
                list.AddRange(batch);
            }            
        }
    }

Solution

  • Change your code to

    public async Task<ActionResult> Index()
    {
       await GetUsersAsync();
       return View(list);
    }
    
    public async Task<Context.Collection> GetUsersAsync()
    {
        var filter = new BsonDocument();
        var collection = Context.Collection();            
        var cursor = await collection.FindAsync(filter);
        while (await cursor.MoveNextAsync())
        {
           var batch = cursor.Current;
           list.AddRange(batch);
        }      
        return list;      
    }
    

    Have also a look at the Using Asynchronous Methods in ASP.NET MVC 4 page.