I'm building an application with an SQL database, with the following CRUD operations:
public Foo Add(Foo foo)
{
_dbContext.Foos.Add(foo);
_dbContext.SaveChanges();
return foo;
}
public Foo Delete(int id)
{
Foo foo = _dbContext.Foos.Find(id);
if(foo != null)
{
_dbContext.Foos.Remove(foo);
_dbContext.SaveChanges();
}
return foo;
}
However, some of these methods have asynchronous versions. The following still works:
public async Task<Foo> Add(Foo foo)
{
await _dbContext.Foos.AddAsync(foo);
await _dbContext.SaveChangesAsync();
return foo;
}
public async Task<Foo> Delete(int id)
{
Foo foo = await _dbContext.Foos.FindAsync(id);
if(foo != null)
{
_dbContext.Foos.Remove(foo);
await _dbContext.SaveChangesAsync();
}
return foo;
}
Is it only necessary when you still need the variable after calling the method?
As in Foo foo = await _dbContext.Foos.FindAsync(id);
What if I'm passing in a list of Foos to add to the database?