实体框架6,.NET框架4.0和SaveChangesAsync [英] Entity Framework 6, .NET Framework 4.0 and SaveChangesAsync

查看:209
本文介绍了实体框架6,.NET框架4.0和SaveChangesAsync的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发的 VS2012 ,目标的.NET Framework 4.0 和使用 EF6

I am developing on VS2012, targeting .NET Framework 4.0 and using EF6.

我已经安装了Microsoft的NuGet包。

I have installed Nuget packages from Microsoft.

 <package id="Microsoft.Bcl" version="1.1.8" targetFramework="net40" />
 <package id="Microsoft.Bcl.Async" version="1.0.168" targetFramework="net40" />
 <package id="Microsoft.Bcl.Build" version="1.0.14" targetFramework="net40" />

我想将更改保存到数据库asynchroniously。 我发现有等待可用,但我找不到 SaveChangesAsync

I'd like to save changes to database asynchroniously. I found there is Await available but I cannot find SaveChangesAsync.

什么我需要做的,使异步操作与框架4.0?

(我不能upgrage为框架4.5,需要坚持使用4.0)

推荐答案

异步功能不包含在.NET 4.0编译EF组装,所以你会必须使用工作中,你叫的SaveChanges

The async functions are not included in the .Net 4.0-compiled EF assembly, so you'll have to use a Task in which you call SaveChanges.

这是英孚的源$ C ​​$ C摘录:

Excerpt from EF's source code:

#if !NET40

        public virtual Task<int> SaveChangesAsync()
        ...

        public virtual Task<int> SaveChangesAsync(CancellationToken cancellationToken)
        ...

#endif

所以,你可以创建这样一个方法:

So you could create a method like this one:

public Task<int> SaveChangesAsync(MyDbContext context)
{
    return Task.Factory.StartNew(() => context.SaveChanges());
}

我想你已经知道的事实,即的DbContext 不是线程安全的,所以你必须确保上下文不用于其他数据库交互的平均时间。

I assume you're aware of the fact that a DbContext is not thread safe, so you'll have to make sure that the context isn't used for other database interactions in the mean time.

这篇关于实体框架6,.NET框架4.0和SaveChangesAsync的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆