Check out my book "Hands-On RESTful Web Services with ASP.NET Core" available on Amazon or Packt. Source code available on GitHub

Entity Framework async query

The purpose of this example is explain how make async query using Entity Framework.

Requirements

This example uses .NET Framework 4.5 (or highter) and Entity Framework 6.0 (or highter). The async and await keywords were introduced in .NET 4.5.

Defining the model

The model describes a product repository. The code below defines two entities : Product and ProductCategory. The repository class needs to extend DbContext and uses DbSet to implement the collection of objects.

Make async query

The code below describes the async query: while the statement await db.SaveChangesAync() write the new product category, main method is continuing the execution.
Since all other execution has completed, the thread will just halt on the task.Wait(). At the end, the QueryAsync() method write results to Console.

Result

Entity Framework query result

Entity Framework query result

About Samuele Resca

Samuele Resca is an Microsoft MVP Visual Studio and Development Technologies, Software Engineer, specializing mainly on ASP.NET MVC and in general about everything that revolves around the web. Samuele was born in 1994, and works as a software developer @ YOOX NET-A-PORTER Group He loves the MVC frameworks, ASP.NET MVC, Javascript, Node.js and Typescript.