ditoslav
ditoslav

Reputation: 4882

Can controller in MVC have async calls to database?

I'm adding a business data layer to my project and currently I'm connecting it to an MVC application. I am going to have controllers which answer to views and controllers which will be for WebApi so that I can make async AngularJS calls.

Do I need to implement both async and sync calls to my data or can I use the async functions for the classic MVC controller? (I'm not sure how the communication between view and controller is implemented so I'm afraid if I might cause some issues since by default it's making sync calls to database)

Upvotes: 0

Views: 339

Answers (1)

Richard
Richard

Reputation: 109130

or can I use the async functions for the classic MVC controller?

You certainly can. At least in the more recent versions of MVC (I cannot recall when support was added).

You don't need to do anything special, just mark your actions async and return Task<ActionResult>.

You can freely mix blocking and asynchronous methods within the action.

Eg.

public async Task<ActionResult> Details(id) {

  var res = await db.Entities.FindAsync(id);
  if (res == null) {
    return HttpNotFound();
  }

  return View(res);
}

Upvotes: 3

Related Questions