Using VS2013, EF6.1.1, MVC5, .net 4.5.
I have just started looking into async/await for the first time and I am not sure if this is doing it properly. It appears to work, but could it be simpler? I seem to be sticking async/await in a lot of places for one method call down multiple layers.
All code has been simplified for brevity.
In my MVC controller action method I have:
public async Task<ActionResult> TestAction1()
{
var testResponse = await _testService.TestMethod1(1);
if (testResponse != null)
{
_unitOfWork.CommitAsync();
return View(testResponse);
}
return RedirectToAction("TestAction2");
}
My service class is as follows:
public class TestService : ITestService
{
public async Task<TestObject> TestMethod1()
{
var testObject1 = await privateMethod1Async();
if (testObject1 != null) return testObject1;
testObject1 = await privateMethod2Async();
return testObject1;
}
private async Task<TestObject> privateMethod1Async()
{
return await _testRepository.FirstOrDefaultAsync();
}
private async Task<TestObject> privateMethod2Async()
{
return await _testRepository.FirstOrDefaultAsync();
}
}
And my repository method:
public async Task<TEntity> FirstOrDefaultAsync()
{
return await _entitySet.FirstOrDefaultAsync();
}
Basically, I have a controller method, that calls a service method. The service method is to call the database layer twice, in an async fashion. But I feel that I am changing every single method and layer to deal with async and I wasn't sure if what I have here is correct.
Secondly, in the controller method I am unsure how to call the unit of work commit method asynchronously. The line that has "_unitOfWork.CommitAsync();". I cannot stick an "await" before it as it is a void method.
Any thoughts?
EDIT 1
Here is the full version of the repository method call to EF:
public async Task<TEntity> FirstOrDefaultAsync(Expression<Func<TEntity, bool>>
predicate, params
Expression<Func<TEntity, object>>[]
includeProperties)
{
IQueryable<TEntity> query = EntitySet;
if (includeProperties != null && includeProperties.Any())
{
query = IncludeProperties(query, includeProperties);
}
return await query.FirstOrDefaultAsync(predicate);
}