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的更多相关文章

  1. Entity Framework 6.0 Tutorials(1):Introduction

    以下系统文章为EF6.0知识的介绍,本章是第一篇 原文地址:http://www.entityframeworktutorial.net/entityframework6/introduction.a ...

  2. 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 ...

  3. Entity Framework 6.0 Tutorials(11):Download Sample Project

    Download Sample Project: Download a sample project for Entity Framework 6 Database-First model below ...

  4. Entity Framework 6.0 Tutorials(10):Index Attribute

    Index Attribute: Entity Framework 6 provides Index attribute to create Index on a particular column ...

  5. Entity Framework 6.0 Tutorials(9):Stored Procedure Mapping

    Code First - Insert, Update, Delete Stored Procedure Mapping: Entity Framework 6 Code-First provides ...

  6. Entity Framework 6.0 Tutorials(6):Transaction support

    Transaction support: Entity Framework by default wraps Insert, Update or Delete operation in a trans ...

  7. Entity Framework 6.0 Tutorials(3):Code-based Configuration

    Code-based Configuration: Entity Framework 6 has introduced code based configuration. Now, you can c ...

  8. 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 ...

  9. Entity Framework 6.0 Tutorials(7):DbSet.AddRange & DbSet.RemoveRange

    DbSet.AddRange & DbSet.RemoveRange: DbSet in EF 6 has introduced new methods AddRange & Remo ...

随机推荐

  1. String类的一些常规方法

    String类 String类常用方法: ①length(): length()       长度    方法** 对比:数组.length      属性** 一般情况下,一个数字,一个字母,一个汉 ...

  2. 也谈TDD,以及三层架构、设计模式、ORM……没有免费的午餐,选择了,必付出代价

    想在园子里写点东西已经很久了,但一直没有落笔,忙着做 一起帮 的开发直播,还有些软文做推广,还要做奶爸带孩子,还要……好吧,我承认,真正的原因是: 太特么的难写了! 但再难写也要写啊,要等到“能写好了 ...

  3. mysql之 explain、optimizer_trace 执行计划

    一.explain mysql> explain select host,user,plugin from user ;+----+-------------+-------+------+-- ...

  4. mysql数据库备份脚本

    mysql数据库备份脚本 mysql数据库分库备份脚本:[root@localhost tmp]# cat mysql.sh #!/bin/bash USER=root PASSWORD=joy4yo ...

  5. 【转】 Pro Android学习笔记(九一):了解Handler(5):组件生命

    文章转载只能用于非商业性质,且不能带有虚拟货币.积分.注册等附加条件.转载须注明出处:http://blog.csdn.net/flowingflying/ 对于activity,消息是在OnCrea ...

  6. java ------------用Array.sort()输出数组元素的最大值,最小值,平均值~~~~

    总结:输出最大值,最小值,可以先排序,再输出就容易点了.不用循环判断.我还没学.但是觉得很好用 package com.aini; import java.util.Arrays; import ja ...

  7. ECMAscript一些方法的使用

    typeof 操作符 来检测 属性是否 都存在 例如:typeof ages.name == "string"  ===>如果是 true 就存在 , 若是 false 就不 ...

  8. pt工具之pt-archiver

    # tar -zxvf percona-toolkit-2.2.17.tar.gz# yum -y install perl perl-IO-Socket-SSL perl-DBD-MySQL per ...

  9. jQueryUI Sortable 应用Demo

    最近工作用需要设计一个自由布局的页面设计.我选了jQuery UI 的 sortable ,可以拖拽,自由排序 使用很方便,写一个demo,做个记录. 第一.单项目自由排序 下图效果 代码段: < ...

  10. 主流ETL工具

    主流ETL产品: Ascential公司的Datastage(Datastage在2005年被IBM收购).Informatica公司的Powercenter. NCR Teradata公司的ETL ...