- Entity F - Nested Entity Types
- Entity F - Multiple DbContext
- Entity F - Code First Migration
- Entity Framework - Seed Database
- Entity Framework - Fluent API
- Entity Framework - Data Annotations
- Entity Framework - First Example
- Entity F - Code First Approach
- Entity Framework - Colored Entities
- Entity Framework - Track Changes
- Entity Framework - Validation
- Entity Framework - Explicit Loading
- Entity Framework - Lazy Loading
- Entity Framework - Eager Loading
- Entity Framework - Migration
- Entity Framework - Inheritance
- Entity Framework - Spatial Data Type
- Entity F - Command Interception
- Entity F - Command Logging
- Entity F - Projection Queries
- Entity Framework - Persistence
- Entity F - Asynchronous Query
- Entity Framework - Enum Support
- Entity Framework - Native SQL
- Entity F - Table-Valued Function
- Entity F - Disconnected Entities
- Entity F - Stored Procedures
- Entity Framework - Index
- Entity Framework - Views
- Entity Framework - Transaction
- Entity Framework - Concurrency
- Entity F - Database Operations
- Entity Framework - DEV Approaches
- Entity F - Database First Approach
- Entity F - Model First Approach
- Entity F - Code First Approach
- Entity Framework - Lifecycle
- Entity Framework - Relationships
- Entity Framework - Types
- Entity Framework - DbContext
- Entity Framework - Data Model
- Entity Framework - Database Setup
- Entity F - Environment Setup
- Entity Framework - Architecture
- Entity Framework - Overview
- Entity Framework - Home
Entity Framework Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Entity Framework - Asynchronous Query
Asynchronous programming involves executing operations in the background so that the main thread can continue its own operations. This way the main thread can keep the user interface responsive while the background thread is processing the task at hand.
Entity Framework 6.0 supports asynchronous operations for querying and saving of data.
Asynchronous operations can help your apppcation in the following ways −
Make your apppcation more responsive to user interactions
Improve the overall performance of your apppcation
You can execute asynchronous operations in various ways. But async/await keywords were introduced in .NET Framework 4.5 which makes your job simple.
The only thing you need to follow is the async/await pattern as illustrated by the following code fragment.
Let’s take a look at the following example (without using async/await) in which DatabaseOperations method saves a new student to the database and then retrieves all students from the database and at the end some additional message is printed on the console.
class Program { static void Main(string[] args) { Console.WriteLine("Database Operations Started"); DatabaseOperations(); Console.WriteLine(); Console.WriteLine("Database Operations Completed"); Console.WriteLine(); Console.WriteLine("Entity Framework Tutorials"); Console.ReadKey(); } pubpc static void DatabaseOperations() { using (var context = new UniContextEntities()) { // Create a new student and save it context.Students.Add(new Student { FirstMidName = "Akram", LastName = "Khan", EnrollmentDate = DateTime.Parse(DateTime.Today.ToString())}); Console.WriteLine("Calpng SaveChanges."); context.SaveChanges(); Console.WriteLine("SaveChanges completed."); // Query for all Students ordered by first name var students = (from s in context.Students orderby s.FirstMidName select s).ToList(); // Write all students out to Console Console.WriteLine(); Console.WriteLine("All Student:"); foreach (var student in students) { string name = student.FirstMidName + " " + student.LastName; Console.WriteLine(" " + name); } } } }
When the above code is executed, you will receive the following output −
Calpng SaveChanges. SaveChanges completed. All Student: Akram Khan Ap Khan Ap Alexander Arturo Anand Bill Gates Gytis Barzdukas Laura Nornan Meredith fllonso Nino Opoetto Peggy Justice Yan Li Entity Framework Tutorials
Let’s use the new async and await keywords and make the following changes to Program.cs
Add System.Data.Entity namespace which will give EF async extension methods.
Add System.Threading.Tasks namespace which will allow us to use the Task type.
Update DatabaseOperations to be marked as async and return a Task.
Call the Async version of SaveChanges and await its completion.
Call the Async version of ToList and await the result.
class Program { static void Main(string[] args) { var task = DatabaseOperations(); Console.WriteLine(); Console.WriteLine("Entity Framework Tutorials"); task.Wait(); Console.ReadKey(); } pubpc static async Task DatabaseOperations() { using (var context = new UniContextEntities()) { // Create a new blog and save it context.Students.Add(new Student { FirstMidName = "Salman", LastName = "Khan", EnrollmentDate = DateTime.Parse(DateTime.Today.ToString())}); Console.WriteLine("Calpng SaveChanges."); await context.SaveChangesAsync(); Console.WriteLine("SaveChanges completed."); // Query for all Students ordered by first name var students = await (from s in context.Students orderby s.FirstMidName select s).ToListAsync(); // Write all students out to Console Console.WriteLine(); Console.WriteLine("All Student:"); foreach (var student in students) { string name = student.FirstMidName + " " + student.LastName; Console.WriteLine(" " + name); } } } }
On execution, it will produce the following output.
Calpng SaveChanges. Entity Framework Tutorials SaveChanges completed. All Student: Akram Khan Ap Khan Ap Alexander Arturo Anand Bill Gates Gytis Barzdukas Laura Nornan Meredith fllonso Nino Opoetto Peggy Justice Salman Khan Yan Li
Now that the code is asynchronous, you can observe a different execution flow of your program.
SaveChanges begins to push the new Student to the database and then the DatabaseOperations method returns (even though it hasn t finished executing) and program flow in the Main method continues.
Message is then written to the console.
The managed thread is blocked on the Wait call until the database operation completes. Once it completes, the remainder of our DatabaseOperations will be executed.
SaveChanges completes.
Retrieved all the student from the database and is written to the Console.
We recommend that you execute the above example in a step-by-step manner for better understanding.
Advertisements