且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

实体框架6,.NET框架4.0和SaveChangesAsync

更新时间:2023-02-07 14:53:26

异步功能不包含在.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.