Link to home
Create AccountLog in
Avatar of sbornstein2
sbornstein2

asked on

ASP.Net MVC IActionResult question

How do I make this an async action result if I am using auto mapper.

        public async Task<IActionResult> Index()
        {
            var items = _context.Customers.ToListAsync();
            var mappedItems = _mapper.Map<List<CustomerViewModel>>(items);

            return View(mappedItems);
        }

The issue is from the context I can use ToListAsync but I can't use the await such as return View(await mappedItems);.   What is the best way to handle this when using automapper?
Avatar of kaufmed
kaufmed
Flag of United States of America image

await the ToListAsync call:

var items = await _context.Customers.ToListAsync();

Open in new window


Basically, await a task wherever you absolutely cannot continue further without the value that the task holds. It doesn't necessarily need to happen on the same line as the async call itself, but in your case it does need to because your mapping code is dependent on that value.
Avatar of sbornstein2
sbornstein2

ASKER

But if I do that then the action result needs to not be async at that point so that was my concern.  I tried that and that did work on the list but the action result then needed to be a regular sync which did not make sense to me.
ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account