Entity Framework 6.0 Tutorials(2):Async query and Save
Async query and Save:
You can take advantage of asynchronous execution of .Net 4.5 with Entity Framework. EF 6 has the ability to execute a query and command asynchronously using DbContext.
Let's see how to execute asynchronous query first and then we will see an asynchronous call to context.SaveChanges.
Asynchronous Query:
- private static async Task<Student> GetStudent()
- {
- Student student = null;
- using (var context = new SchoolDBEntities())
- {
- Console.WriteLine("Start GetStudent...");
- student = await (context.Students.Where(s => s.StudentID == ).FirstOrDefaultAsync<Student>());
- Console.WriteLine("Finished GetStudent...");
- }
- return student;
- }
As you can see in the above code, GetStudent method is marked with async to make it asynchronous. The return type of asynchrounous method must be Task. GetStudent returns an object of Student entity so return type must be Task<Student>.
Also, query is marked with await. This frees the calling thread to do something else until it executes the query and returns the data. We have used FirstOrDefaultAsync extension method of System.Data.Entity. You may use other extension methods appropriately, such as SingleOrDefaultAsync, ToListAsyn, etc.
Asynchronous Save:
You can call context.SaveChanges asynchronously the same way as async query:
- private static async Task SaveStudent(Student editedStudent)
- {
- using (var context = new SchoolDBEntities())
- {
- context.Entry(editedStudent).State = EntityState.Modified;
- Console.WriteLine("Start SaveStudent...");
- int x = await (context.SaveChangesAsync());
- Console.WriteLine("Finished SaveStudent...");
- }
- }
Getting async query result:
You can get the result when asynchronous using the wait method as below:
- public static void AsyncQueryAndSave()
- {
- var student = GetStudent();
- Console.WriteLine("Let's do something else till we get student..");
- student.Wait();
- var studentSave = SaveStudent(student.Result);
- Console.WriteLine("Let's do something else till we get student.." );
- studentSave.Wait();
- }
As shown in the code above, we call async method GetStudent in the usual way and store the reference in the variable student. Then, we call student.wait(). This means that the calling thread should wait until the asynchronous method completes, so we can do another process, until we get the result from the asynchronous method.
The code shown above will have the following output:
Download sample project for Async query & save demo.
Entity Framework 6.0 Tutorials(2):Async query and Save的更多相关文章
- Entity Framework 6.0 Tutorials(1):Introduction
以下系统文章为EF6.0知识的介绍,本章是第一篇 原文地址:http://www.entityframeworktutorial.net/entityframework6/introduction.a ...
- Entity Framework 6.0 Tutorials(4):Database Command Logging
Database Command Logging: In this section, you will learn how to log commands & queries sent to ...
- Entity Framework 6.0 Tutorials(11):Download Sample Project
Download Sample Project: Download a sample project for Entity Framework 6 Database-First model below ...
- Entity Framework 6.0 Tutorials(10):Index Attribute
Index Attribute: Entity Framework 6 provides Index attribute to create Index on a particular column ...
- Entity Framework 6.0 Tutorials(9):Stored Procedure Mapping
Code First - Insert, Update, Delete Stored Procedure Mapping: Entity Framework 6 Code-First provides ...
- Entity Framework 6.0 Tutorials(6):Transaction support
Transaction support: Entity Framework by default wraps Insert, Update or Delete operation in a trans ...
- Entity Framework 6.0 Tutorials(3):Code-based Configuration
Code-based Configuration: Entity Framework 6 has introduced code based configuration. Now, you can c ...
- Entity Framework 6.0 Tutorials(8):Custom Code-First Conventions
Custom Code-First Conventions: Code-First has a set of default behaviors for the models that are ref ...
- Entity Framework 6.0 Tutorials(7):DbSet.AddRange & DbSet.RemoveRange
DbSet.AddRange & DbSet.RemoveRange: DbSet in EF 6 has introduced new methods AddRange & Remo ...
随机推荐
- BZOJ3632: 外太空旅行
BZOJ1547: 周末晚会 https://lydsy.com/JudgeOnline/problem.php?id=1547 分析: 对于一个串旋转若干次会回到本身,旋转次数即是同构个数,这个东西 ...
- HTML <meta> http-equiv Attribute 说明
1. 说明 Value Description content-type Specifies the character encoding for the document. Example: & ...
- gitlab pipelines 使用
1. 安装runner # For Debian/Ubuntu curl -L https://packages.gitlab.com/install/repositories/runner/gi ...
- iframe添加点击事件
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content ...
- PL/Sql developer安装,设置
安装PL/Sql developer,和安装出现错误(oracle client not properly installed),pl/sql中文乱码 下载安装plsql_dev(文末有64位的百度云 ...
- BroadcastReceiver用法
动态注册广播接收器 1.创建一个Receiver继承BroadcastReceiver,并重写onReceiver() 2.在Activity的OnCreate()中添加广播接收器想要接收的actio ...
- PHP获取路径
//获取域名或主机地址 echo $_SERVER['HTTP_HOST']."<br>"; #jiqing.nikon.com echo 'http://'.$_SE ...
- PHP判断文件是否被引入的方法get_included_files
<?php // 本文件是 abc.php include 'test1.php'; include_once 'test2.php'; require 'test3.php'; require ...
- Oracle常见的表连接的方法
1 排序合并连接SMJ Sort merge join 排序合并总结: 1 通常情况下,排序合并连接的效率远不如hash join,前者适用范围更广,hj只使用于等值连接,smj范围更广(<,& ...
- python开发进程:互斥锁(同步锁)&进程其他属性&进程间通信(queue)&生产者消费者模型
一,互斥锁,同步锁 进程之间数据不共享,但是共享同一套文件系统,所以访问同一个文件,或同一个打印终端,是没有问题的, 竞争带来的结果就是错乱,如何控制,就是加锁处理 part1:多个进程共享同一打印终 ...