Entity Framework异步查询和保存
EF6开始提供了通过async和await关键字实现异步查询和保存的支持(.net 4.5及更高版本)。虽然不是所有的操作都能从异步中获益,但是耗时的操作、网络或IO密集型任务中,使用异步可以提升客户端性能和增强服务器的扩展性。
本文将覆盖一下主题:
- 实例演练异步操作
- 创建模型
- 创建同步程序
- 改为异步操作
实例演练异步操作
下面演练将通过对比,很容易的观察异步操作和同步操作,该演练目的不是说明何时才是异步操作的关键场景。
创建模型
下面使用CodeFirst的流程创建模型并生成数据库,不过异步方法可以很好的工作于所有EF模型,包括EF设计器生成的模型。
创建一个控制台应用程序AsyncDemo。
添加EntityFramework NuGet包到项目中。
添加Model.cs到项目中,代码如下:
using System.Collections.Generic;
using System.Data.Entity; namespace AsyncDemo
{
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
} public class Blog
{
public int BlogId { get; set; }
public string Name { get; set; } public virtual List<Post> Posts { get; set; }
} public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; } public int BlogId { get; set; }
public virtual Blog Blog { get; set; }
}
}
创建同步程序
有了EF模型,下面通过代码模拟数据库存取。
using System;
using System.Linq; namespace AsyncDemo
{
class Program
{
static void Main(string[] args)
{
PerformDatabaseOperations(); Console.WriteLine();
Console.WriteLine("Quote of the day");
Console.WriteLine(" Don't worry about the world coming to an end today... ");
Console.WriteLine(" It's already tomorrow in Australia."); Console.WriteLine();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
} public static void PerformDatabaseOperations()
{
using (var db = new BloggingContext())
{
// Create a new blog and save it
db.Blogs.Add(new Blog
{
Name = "Test Blog #" + (db.Blogs.Count() + )
});
db.SaveChanges(); // Query for all blogs ordered by name
var blogs = (from b in db.Blogs
orderby b.Name
select b).ToList(); // Write all blogs out to Console
Console.WriteLine();
Console.WriteLine("All blogs:");
foreach (var blog in blogs)
{
Console.WriteLine(" " + blog.Name);
}
}
}
}
}
上面代码通过调用PerformDatabaseOperations() 保存一个Blog对象到数据库中,然后从数据库中检索所有Blog,并显示到控制台,然后显示一行文本”Quote of the day“。
由于上面程序是同步执行的,所有可以观察到程序按下面流程执行:
- SaveChanges保存Blog对象到数据库中。
- SaveChanges完成。
- 发送查询Blog请求到数据库。
- 查询返回结果,并写入控制台。
- 显示文本“Quote of the day”到控制台。

改造为异步操作
对上面程序加以修改,使用async和await关键字实现异步操作。
using System;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks; namespace AsyncDemo
{
class Program
{
static void Main(string[] args)
{
var task = PerformDatabaseOperations(); Console.WriteLine("Quote of the day");
Console.WriteLine(" Don't worry about the world coming to an end today... ");
Console.WriteLine(" It's already tomorrow in Australia."); task.Wait(); Console.WriteLine();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
} public static async Task PerformDatabaseOperations()
{
using (var db = new BloggingContext())
{
// Create a new blog and save it
db.Blogs.Add(new Blog
{
Name = "Test Blog #" + (db.Blogs.Count() + )
});
Console.WriteLine("Calling SaveChanges.");
await db.SaveChangesAsync();
Console.WriteLine("SaveChanges completed."); // Query for all blogs ordered by name
Console.WriteLine("Executing query.");
var blogs = await (from b in db.Blogs
orderby b.Name
select b).ToListAsync(); // Write all blogs out to Console
Console.WriteLine("Query completed with following results:");
foreach (var blog in blogs)
{
Console.WriteLine(" - " + blog.Name);
}
}
}
}
}
现在程序变为异步执行,可以观察到异步执行顺序为:
- 发送SaveChanges请求到数据库。
- 该请求发送给数据库时,当前线程不在占用CPU时间,从方法PerformDatabaseOperations中返回(虽然该方法还没有执行完成),控制权返回给主线程执行。
- 显示字符串“Quote of the day ”到控制台。
- SaveChanges完成。
- 发起查询Blogs请求到数据库。
- 查询完成返回结果,并显示到控制台。

Entity Framework异步查询和保存的更多相关文章
- 整理一下Entity Framework的查询
整理一下Entity Framework的查询 2012-08-30 13:41:59 标签:Entity Framework 原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信 ...
- Entity Framework 简单查询
前言 首先来简单的复习一下如何使用Code First. 第一步还是先建立一个控制台的应用程序,然后通过Nuget添加Entity Framework.那么同时会给packages.config和Ap ...
- 整理一下Entity Framework的查询 [转]
Entity Framework是个好东西,虽然没有Hibernate功能强大,但使用更简便.今天整理一下常见SQL如何用EF来表达,Func形式和Linq形式都会列出来(本人更喜欢Func形式). ...
- 转:整理一下Entity Framework的查询
Entity Framework是个好东西,虽然没有Hibernate功能强大,但使用更简便.今天整理一下常见SQL如何用EF来表达,Func形式和Linq形式都会列出来(本人更喜欢Func形式). ...
- Entity Framework的查询
Entity Framework是个好东西,虽然没有Hibernate功能强大,但使用更简便.今天整理一下常见SQL如何用EF来表达,Func形式和Linq形式都会列出来(本人更喜欢Func形式). ...
- Entity Framework关联查询以及数据加载(延迟加载,预加载)
数据加载分为延迟加载和预加载 EF的关联实体加载有三种方式:Lazy Loading,Eager Loading,Explicit Loading,其中Lazy Loading和Explicit Lo ...
- Entity Framework (二) 查询
待完善-------------------------------------- ----------- base 关键字用于从派生类中访问基类的成员: 调用基类上已被其他方法重写的方法. 指定创建 ...
- Entity Framework: 视图查询时重复返回第一行值, duplicate frst rows in resultset from a view
http://blog.csdn.net/riverlau/article/details/7476449 1. 使用rownumber给view加上一个标示列 SELECT ROW_NUMBER() ...
- 《Entity Framework 6 Recipes》中文翻译系列 (41) ------ 第七章 使用对象服务之标识关系中使用依赖实体与异步查询保存
翻译的初衷以及为什么选择<Entity Framework 6 Recipes>来学习,请看本系列开篇 7-7 标识关系中使用依赖实体 问题 你想在标识关系中插入,更新和删除一个依赖实体 ...
随机推荐
- easyui datagrid editor onBeforeEdit事件下使用getEditor和getEditors失效
我在使用onClickRow: function(rowIndex,rowData){ if(editRow!=-1){ ...
- mysql语句与sql语句的基本区别
. MySQL支持enum和set类型,SQL Server不支持: . MySQL不支持nchar.nvarchar.ntext类型: . MySQL数据库的递增语句是AUTO_INCREMENT, ...
- .net core 2.0的一次奇特经历
环境:.net core SDK版本 2.0.0-preview1-005977 VS 2017 version 15.3.0 preview 3.0 问题描述:今天在迁移Job的项目中,中午吃饭的时 ...
- Elasticsearch-PHP 索引操作2
索引操作 索引在客户端非常容易.因为关联数组很容易转换为JSON文档,索引文档只是提供正确和结构性的关联数组和调用方法. 单文档索引 当你索引你个文档时,可以自己提供一个ID,也可以让elastics ...
- 使apk具有system权限
使apk具有system权限的方法: 方法一: 1. 在应用程序的AndroidManifest.xml中的manifest节点中加入 android:sharedUserId=" ...
- SpringMVC单元测试-MockMvc
一 简介 MockMvc实现对Http请求的模拟,可以方便对Controller进行测试,使得测试速度快.不依赖网络环境,而且提供验证的工具,使得请求的验证统一而且很方便. 二 常见使用方式 1 ...
- Opencv normalize
#include <iostream>#include <opencv2/opencv.hpp> using namespace std;using namespace cv; ...
- windows下的phpunit安装
Windows Globally installing the PHAR involves the same procedure as manually installing Composer on ...
- java工具jar包—Lombok
如何引入 maven工程,直接引入lombok的jar依赖即可: <dependency> <groupId>org.projectlombok</groupId> ...
- [SoapUI] SOAP UI-Groovy Useful Commands
Hi All, I have posted the SOAPUI and Groovy useful commands that may help you in your testing. Below ...