Why does no one disposes DbContext after WebApi controller operation?

后端 未结 6 2525
梦谈多话
梦谈多话 2021-02-19 20:32

I am aware of various tutorials as well as complete examples targeting WebApi & Entity Framework (even from Microsoft) that have WebApi

6条回答
  •  时光取名叫无心
    2021-02-19 20:43

    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.

提交回复
热议问题