I am not sure how to use using statement correct.
I try like this:
[HttpDelete("{ClubId}", Name = "DeleteOpenings_Club")]
public async Task<IActionResult> DeleteClub_IsOpening([FromRoute] string ClubId)
{
using (_db_ClubIsOpen)
{
var result = _db_ClubIsOpen.ClubIsOpen_TBL.Where(x => x.FK_Club == ClubId);
foreach (var item in result)
{
_db_ClubIsOpen.ClubIsOpen_TBL.Remove(item);
}
_db_ClubIsOpen.SaveChanges();
return Ok();
}
}
using
is tied into lifetime management, which is a complex question.
Usually, the usage of using
you're deploying here would be for things that your method owns; for example, here:
using (var dbContext = new DbContext(whatever))
{
// some code
}
(or just using var dbContext = new DbContext(whatever);
in recent C# versions)
In the above, we are clearly creating the thing, so it is our job to make sure that it gets disposed, which is happening thanks to the using
.
However, in the example in the question, it isn't clear what _db_ClubIsOpen
is, or what the lifetime is, or who owns it. By default, I would absolutely not assume that a method is responsible for taking ownership of an arbitrary field, so I would not expect to use using
here, in the sense of using (_someField)
as shown in the question. Instead, I would expect either some DI/IoC framework to deal with that (if it is being injected), or I would expect the type to implement IDipsosable
, and deal with disposing the field in Dispose()
.