Entity Framework 6, .NET Framework 4.0 and SaveCha

2019-08-05 07:56发布

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

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" />

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

What do I need to do to enable async operations with Framework 4.0 ?

(I cannot upgrage to Framework 4.5 and need to stick with 4.0)

1条回答
2楼-- · 2019-08-05 08:26

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.

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());
}

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.

查看更多
登录 后发表回答