I am aware of various tutorials as well as complete examples targeting WebApi
& Entity Framework
(even from Microsoft) that have WebApi
Sometimes it is a bad idea to dispose the context. For example, I have a WebAPI2 controller method like this,
[Route("Questionnaires")]
public IEnumerable GetAllQuestionnaires()
{
NMQContext context = new NMQContext();
return context.Questionnaires.AsEnumerable();
}
The result data is a JSON list, and the Questionnaire is a compound object -- it contains entities from multiple database tables. If I wrap this with "using" I get an error, such as
"Message": "An error has occurred.",
"ExceptionMessage": "The operation cannot be completed because the DbContext has been disposed.",
If you are trying to serialize compound objects, then it is better NOT to dispose the connection. It is better to let the EF handle it for you. You could probably fix it by explicit eager loading, but that is painful. Don't do it.