Why does no one disposes DbContext after WebApi controller operation?

后端 未结 6 2524
梦谈多话
梦谈多话 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:57

    Prime case for using, no matter how the method is exited, your DbContext will be disposed;

    public HttpResponseMessage GetInternet(int id) {
        using(var context = new InternetDbContext()) {
            var result =
               (from internet in context.Internets
                where internet.Id.Equals(id)
                select internet).FirstOrDefault();
            if(result != null)
               Request.CreateResponse(HttpStatusCode.OK, result);
        }
    }
    

提交回复
热议问题