Entity Framework 6, .NET Framework 4.0 and SaveChangesAsync

.net asynchronous entity-framework-6 visual-studio-2012

Question

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
1
1/2/2015 2:06:52 PM

Popular Answer

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.

0
1/2/2015 3:03:14 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow