Scaffolding asynchronous MVC and Web API controllers for Entity Framework 6

Brief

Entity Framework 6 introduces support for the .NET 4.5 asynchronous programming pattern using the async and await keywords. And in Visual Studio 2013 RC we’re making it easier for you to take advantage of this new capability by optionally generating asynchronous code when you scaffold MVC and Web API controllers.

Why

First thing first. Why would you build an asynchronous controller? Well, asynchronous programming is an important part of building scalable, robust, and responsive web applications.

A web server has a limited number of threads available, and in high load situation all of the available threads might be in use. When that happens, the server can’t process new requests until the threads are freed up. With synchronous code, many threads may be tied up while they aren’t actually doing any work because they’re waiting for I/O to complete. With asynchronous code, when a process is waiting for I/O to complete, its thread is freed up for the server to use for processing other requests. As a result asynchronous code enables server resources to be used more efficiently, and the server is enabled to handle more traffic without delays.

For more information about asynchronous programming, see the tutorial Using Asynchronous Methods in ASP.NET MVC 4[ii] and the video How to Build ASP./NET Web Application Using Async[iii].

How

The MVC and Web API controller scaffolders have a new Use async controller actions check box.
The selection will be remembered next time you use the scaffolder.

MVC Controller using Entity Framework


 

Web API 2 Controller / OData Controller using Entity Framework

What

Following is the sample code generated by the scaffolders. The scaffolders generate code to read, create, update and delete data, using the Entity Framework data context.

Read

When you select the async option, the method is marked as “async”, the EF async API is called, and the “await” keyword is used when calling the EF API.

Create

Update

Delete