Working With Asynchronous Programming With Entity Framework


Today we'll learn how to do asynchronous programming with the Entity Framework. We can perform the execution of the application in the background using asynchronous programming so that the main thread can continue its operations. We can get better performance using asynchronous programming. For example, the main operation can keep the user interface responsive and use asynchronous programming in the background task to do other processing.
In the same context, the async and await keywords are defined by the .NET framework with which we can easily perform the asynchronous programming. The latest version of Entity Framework, Entity Framework 6, also has the ability to support the asynchronous operations for querying the data.

Using Async/Await

Using these asynchronous methods we can do two things: first, we can make the application responsive, and second, we can improve the performance of the application. These methods are also useful for desktop applications as well as web applications.
For example:
  1. public async static Task<List<Student>> GetAllStudentsAsync()  
  2. {  
  3.     MyDatabaseEntities db = new MyDatabaseEntities();  
  4.     var query = from item in db.Students  
  5.                 select item;  
  6.     return await query.ToListAsync();  

As you can see in the preceding, the async and await keywords are used. There is some LINQ statements defined in the code above that are explained later in this article.

Performing Asynchronous CRUD Operations

In this section we'll perform the Create, Read, Update and Delete (CRUD) operations. In here we'll use asynchronous programming with the Entity Framework. So, let's develop the application using the following procedure:
  • Open Visual Studio 2013 or 2012
  • Create a New Project
  • Create Console Application
Use the following procedure.
Adding Entity Data Model
In this section, we'll add the ADO.NET Entity Data Model to the application.
Step 1: Just right-click on the application and add the ADO.NET Entity Data Model.
Selecting Model in Entity Data Model
Step 2: Select the table to work with after defining the connection string.
Selecting Objects in Entity Model
That's it. We have successfully added the data model to the application. You can see it from the Model diagram as in the following:
Entity Model

Working with Asynchronous Programming

Since we are about to perform the CRUD operations here so if we perform it without the asynchronous programming it'll look like the following structure:
  1. public static List<Student> GetAllStudent()  
  2. {  
  4. }  
  6. public static Student GetStudent(int id)  
  7. {  
  9. }  
  11. public static string InsertStudent(Student student)  
  12. {  
  14. }  
  16. public static string UpdateStudent(Student student)  
  17. {  
  19. }  
  21. public static string DeleteStudent(int id)  
  22. {  

But in here we need to perform the task with asynchronous programming, so for doing the asynchronous programming we need to use the asynchronous methods as in the following:
  1. public async static Task<List<Student>> GetAllStudentsAsync()  
  2. {  
  3.     MyDatabaseEntities db = new MyDatabaseEntities();  
  4.     var query = from item in db.Students  
  5.                 select item;  
  6.     return await query.ToListAsync();  

In the code above, the method named has the proper naming convention of the async method as GetAllStudentsAsync(). The async keyword specifies that the method is an asynchronous method. The await keyword is also necessary for this method. We called the ToListAsync() instead of calling ToList() method since we call normally to get the list of records.
Use the following procedure to work with the same context.
Step 1: Add a class in the application named StudentHelper.
Adding Class in the Project
Step 2: Replace the code with the code given below:
  1. using System.Collections.Generic;  
  2. using System.Data.Entity;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  6. namespace ConsoleApplication2  
  7. {  
  8.     class StudentHelper  
  9.     {  
  10.         public async static Task<List<Student>> GetAllStudentsAsync()  
  11.         {  
  12.             MyDatabaseEntities db = new MyDatabaseEntities();  
  13.             var query = from item in db.Students  
  14.                         select item;  
  15.             return await query.ToListAsync();  
  16.         }  
  18.         public async static Task<Student> GetStudentAsync(int id)  
  19.         {  
  20.             MyDatabaseEntities db = new MyDatabaseEntities();  
  21.             var query = (from item in db.Students  
  22.                          where item.ID == id  
  23.                          select item).SingleOrDefaultAsync();  
  24.             return await query;  
  25.         }  
  27.         public async static Task<string> InsertStudentAsync(Student student)  
  28.         {  
  29.             MyDatabaseEntities db = new MyDatabaseEntities();  
  30.             db.Students.Add(student);  
  31.             await db.SaveChangesAsync();  
  32.             return "Student Added Successfully";  
  33.         }  
  35.         public async static Task<string> UpdateStudentAsync(Student student)  
  36.         {  
  37.             MyDatabaseEntities db = new MyDatabaseEntities();  
  38.             Student EditStudent = await db.Students.FindAsync(student.ID);  
  39.             EditStudent.Name = student.Name;  
  40.             EditStudent.Sex = student.Sex;  
  41.             EditStudent.City = student.City;  
  42.             await db.SaveChangesAsync();  
  43.             return "Student Updated Successfully";  
  44.         }  
  46.         public static async Task<string> DeleteStudentAsync(int id)  
  47.         {  
  48.             MyDatabaseEntities db = new MyDatabaseEntities();  
  49.             Student DeleteStudent = await db.Students.FindAsync(id);  
  50.             db.Students.Remove(DeleteStudent);  
  51.             await db.SaveChangesAsync();  
  52.             return "Student Deleted Successfully";  
  53.         }  
  54.     }  

In the code above, the following are the various async methods used:
  • SingleOrDefaultAsync(): Get a single object as a result
  • FindAsync(): Asynchronously finds the entity with the given primary key value.
  • SaveChangesAsync(): Asynchronously save all changes.
Step 3: In the Main() add the following code:
  1. static void Main(string[] args)  
  2. {  
  3.     var query = StudentHelper.GetAllStudentsAsync();  
  4.     query.Wait();  
  5.     List<Student> data = query.Result;  
  6.     Console.WriteLine("Total Records in Students Table are:" + " " + data.Count);  
  7.     Console.ReadLine();              

Step 4: Just run the application
Console Application Execution
If we perform this is the MVC application then we need to write the following code in the controller:
  1. public async Task<ActionResult> Index()  
  2. {  
  3.     List<Student> data = await StudentHelper.GetAllStudentsAsync();  
  4.     return View(data);  

That's it.


This article described how to use asynchronous programming with the Entity Framework in the Console Application. We can also use this in desktop and as well as web applications. We have shown the use of some async methods in this article. So, just use this in your application. Thanks for the application.