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 标识关系中使用依赖实体 问题 你想在标识关系中插入,更新和删除一个依赖实体 ...
随机推荐
- deep learning and machine learning
http://blog.csdn.net/xiangz_csdn/article/details/54580053
- python 协程 gevent 简单测试
串行测试 from gevent import monkey; monkey.patch_all()#有IO才做时需要这一句 import gevent import requests,time st ...
- Git 搭建私有仓库
简介: 如果你不想把自己的代码公开让别人阅读.使用,也不想花钱购买 GitHub 私有仓库,那么你就需要自己动手做一个了. 当然你也可以使用 Coding.net ,上面可以创建免费的私有仓库.( 今 ...
- android学习-Eclipse中修改Android项目图标
参考原文:http://blog.csdn.net/wpwbb510582246/article/details/52556753 方法一:替换res文件夹下的ic_launcher-web.png图 ...
- popup non topmost
public class PopupNonTopmost : Popup { public static DependencyProperty TopmostProperty = Window.Top ...
- 自动补齐flexselect+级联下拉框案例
在开发web应用时,经常遇到类似省市区级联下拉框操作,即选中省份自动级联加载该省份所有的市,选中市自动级联加载该市所有的区:假设省市区的数据量很大,此时用户想选中某市,因而要从上往下查找,可能半天都找 ...
- Spark会产生shuffle的算子
去重 def distinct() def distinct(numPartitions: Int) 聚合 def reduceByKey(func: (V, V) => V, numParti ...
- Apache Hive (七)Hive的DDL操作
转自:https://www.cnblogs.com/qingyunzong/p/8723271.html 库操作 1.创建库 语法结构 CREATE (DATABASE|SCHEMA) [IF NO ...
- Hibernate其它API
----------------siwuxie095 (一)Query 1.使用 Query 对象执行查询操作,不需要写 sql 语句,但是要写 hql 语句 (1)hql:即 Hibernate Q ...
- H5 css学习
p{text-indent:2em;}段前空两格 段落排版--行间距(行高) p{line-height:1.5em;} 段落排版--中文字间距.字母间距 h1{ letter-spaci ...