OdeToCode IC Logo

Async in Entity Framework 6.0

Tuesday, August 28, 2012

If you pull the latest Entity Framework source from CodePlex, you can take a look at some of the features being added for the next version of EF. These features include an async API for DbContext (SaveChangesAsync and ExecuteSqlCommandAsync), as well as async operations on IQueryable<T> through some new extension methods.

Here is how the async version of SaveChanges looks in an ASP.NET MVC controller action:

[HttpPost]
public async Task<ActionResult> Edit(Thing thing)
{
if(ModelState.IsValid)
{
_db.Entry(thing).State = EntityState.Modified;
await _db.SaveChangesAsync();
return RedirectToAction("Index");
}

return View(thing);
}

The new IQueryable operators are async versions of operators that materialize a concrete result. For example, finding a single entity:

[HttpGet]
public async Task<ActionResult> Edit(int id)
{
var model = await _db.Things.FindAsync(id);
// or
var model = await _db.Things.SingleAsync(t => t.Id == id);

return View(model);
}

Also forcing execution with ToList:

public async Task<ActionResult> Index()
{
var model = new HomeIndexViewModel();
model.Things = await _db.Things.ToListAsync();

return View(model);
}

Getting an application up and running with EF 6 (including migrations) is slightly challenging, but I've found the easiest approach is to msbuild the Nuget.proj file in the NuGet directory, then adding the NuGet\bin\debug directory as a custom local NuGet repository and adding references to EF 6 via NuGet. I also had to register all the EF assemblies for verification skipping with sn -Vr.