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 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:
- public async static Task<List<Student>> GetAllStudentsAsync()
- {
- MyDatabaseEntities db = new MyDatabaseEntities();
- var query = from item in db.Students
- select item;
- 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.
Step 2: Select the table to work with after defining the connection string.
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:
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:
- public static List<Student> GetAllStudent()
- {
-
- }
-
- public static Student GetStudent(int id)
- {
-
- }
-
- public static string InsertStudent(Student student)
- {
-
- }
-
- public static string UpdateStudent(Student student)
- {
-
- }
-
- public static string DeleteStudent(int id)
- {
-
- }
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:
- public async static Task<List<Student>> GetAllStudentsAsync()
- {
- MyDatabaseEntities db = new MyDatabaseEntities();
- var query = from item in db.Students
- select item;
- 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.
Step 2: Replace the code with the code given below:
- using System.Collections.Generic;
- using System.Data.Entity;
- using System.Linq;
- using System.Threading.Tasks;
-
- namespace ConsoleApplication2
- {
- class StudentHelper
- {
- public async static Task<List<Student>> GetAllStudentsAsync()
- {
- MyDatabaseEntities db = new MyDatabaseEntities();
- var query = from item in db.Students
- select item;
- return await query.ToListAsync();
- }
-
- public async static Task<Student> GetStudentAsync(int id)
- {
- MyDatabaseEntities db = new MyDatabaseEntities();
- var query = (from item in db.Students
- where item.ID == id
- select item).SingleOrDefaultAsync();
- return await query;
- }
-
- public async static Task<string> InsertStudentAsync(Student student)
- {
- MyDatabaseEntities db = new MyDatabaseEntities();
- db.Students.Add(student);
- await db.SaveChangesAsync();
- return "Student Added Successfully";
- }
-
- public async static Task<string> UpdateStudentAsync(Student student)
- {
- MyDatabaseEntities db = new MyDatabaseEntities();
- Student EditStudent = await db.Students.FindAsync(student.ID);
- EditStudent.Name = student.Name;
- EditStudent.Sex = student.Sex;
- EditStudent.City = student.City;
- await db.SaveChangesAsync();
- return "Student Updated Successfully";
- }
-
- public static async Task<string> DeleteStudentAsync(int id)
- {
- MyDatabaseEntities db = new MyDatabaseEntities();
- Student DeleteStudent = await db.Students.FindAsync(id);
- db.Students.Remove(DeleteStudent);
- await db.SaveChangesAsync();
- return "Student Deleted Successfully";
- }
- }
- }
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:
- static void Main(string[] args)
- {
- var query = StudentHelper.GetAllStudentsAsync();
- query.Wait();
- List<Student> data = query.Result;
- Console.WriteLine("Total Records in Students Table are:" + " " + data.Count);
- Console.ReadLine();
- }
Step 4: Just run the application
If we perform this is the MVC application then we need to write the following code in the controller:
- public async Task<ActionResult> Index()
- {
- List<Student> data = await StudentHelper.GetAllStudentsAsync();
- 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.