I am working on an asp.net mvc5 web application + Entity Framework 6. and I want to have a repository model class inside my application. currently I am following this approach to have async action methods and async repository model class.
for example I have the following repository save method:
public class Repository
{
private Entities t = newEntities();
public async Task Save()
{
await t.SaveChangesAsync();
}
which I am calling from my action methods as follow:
Repository repository = new Repository();
public async Task<ActionResult> GetResourceByName(string resourcename)
{
await repository.Save();
}
so is this a correct approach? as I am doing the following:
I define the repository method as a Task & also the Action method as Task. so should I have both of them as Task(s).?
I am using await
twice on the action method (when calling the repo method) and on the repository? so are these await
redundant?
//please note that this is only a simple example of a repository method which is just used to save model,, but I am asking about the approach itself as I will be using this approach in a more complex repository methods ..
Contrary to both answers two awaits
are not necessary. await
and async
are only necessary if you need the result from a Task
before continuing. If you don't need that result then you don't need to mark your method async
.
This means this method...
public async Task Save()
{
await t.SaveChangesAsync();
}
Can be simplified into
public Task Save()
{
return t.SaveChangesAsync();
}
Even though these are functionally the same, I like the second version because it shows recognition that Task
is the asynchronous work and async/await are only signals to the compiler to wait for that work to complete.