懒加载的深刻理解和处理错误.NET MVC [英] Deep understanding of lazy loading and disposing error in MVC .net

查看:304
本文介绍了懒加载的深刻理解和处理错误.NET MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个全面详细的回答了以下问题:
<一href=\"http://stackoverflow.com/questions/23110719/why-does-dispose-work-and-not-usingvar-db-new-datacontext\">Why的确&QUOT;配置&QUOT;工作中,而不是与QUOT;使用(VAR DB =新的DataContext())&QUOT;?

i was trying to write a full detailed answer to the following question: Why does "Dispose" work, and not "using(var db = new DataContext())"?

所以我成立了我的项目,其中包括:

so I set up my project that include:

使用实体框架,部门和员工

Departments and employees using entity framework

所以我的操作方法是这样的:

so my action method was this:

public ActionResult Index()
    {

        IEnumerable<department> d;
        using (var ctx = new ApplicationDbContext())
        {

            d = ctx.departments;

        }


        return View(d);
}

这是很自然的期望,这将导致常见的错误:

it is natural to expect that this will result in the common error :

The operation cannot be completed because the DbContext has been disposed

和时,我想解决这个问题我做了以下[给力预先加载,而不是简单的装填]:

and when i wanted to resolve it I did the following [to force eager loading rather than easy loading] :

 public ActionResult Index()
    {

        IEnumerable<department> d;
        using (var ctx = new ApplicationDbContext())
        {

            d = ctx.departments.toList();

        }


        return View(d);
}

所以我想了解的引擎盖下的东西,看着查看()方法的返回类型。我伸手以下'的正确'假设:

1-模型[D]。被称为using语句内延迟加载的方式。

2-所以在型号并[d]被发送到视图用于产生的DbContext已经设置在由使用语句的最后大括号的页面。

3,我们通过发送模型[D]与预先加载时尚的观点解决这种情况。

然后我继续我的假设被证明是错误如下:

then I continued my assumptions that proved to be 'wrong' as following:

4-由于视图()方法返回的ViewResult对象,它是一个ActionResult also..then我可以生成using语句里面这个对象,然后返回给用户。

所以我做了以下内容:

public ActionResult Index()
    {

        ActionResult myView;

        using (var ctx = new ApplicationDbContext())
        {

            IEnumerable<department> d = ctx.departments;

            myView =  View(d);

        }


        return myView;
    }

所以现在我告诉我自己,当我运行它,该对象的ViewResult [MyView的]将已经创建,将被返回给用户,并没有遇到错误。

so I told myself now when I run it , the ViewResult object [ myView] will be already created and will be returned to the user and No Error will be encountered.

不过,我感到惊讶的是同样的错误发生:

However I was surprised that the same error occured :

The operation cannot be completed because the DbContext has been disposed

我很惊讶这个延迟加载怎么只有在最后一刻真的懒惰和负载。

I was astonished how this lazy loading is really lazy and load only at the last moment.

于是我继续'的错误的假设如下:

So I continued my 'wrong' assumptions as follow:

5可能是我需要强制视图()方法来EXCUTE using语句内的结果。所以我采用的方法的ExecuteReuslt(ControllerContext)

现在我想我可以没有任何错误运行的操作方法
但再次相同的错误发生:

and now I thought I can run the action method without any error but again the same error occured:

The operation cannot be completed because the DbContext has been disposed.

所以现在我的问题是:

So my question now is:

在MVC框架在那里确实发生延迟加载查询excution !!

还是让我改我的问题如下:

or let me rephrase my question as follow:

为什么视图(D)方法遍历[D]。对象时,它是不可能的使用说明书,而不是当视图(D)方法是using语句里面。

Why did View(d) method iterate over the [d] object when it is out of the using statment, and not when the view(d) method is inside the using Statement.

我只需要明白,为什么我的假设是错误的..
感谢名单先进

I just need to understand why my assumptions were wrong .. Thanx in advanced

推荐答案

确定。我发现了一个非常有说服力的回答如下:

Ok. I found a very convincing answer as follow:

我开始阅读关于MVC5生命周期,发现在网上很多文章。其中之一就是以下链接:http://www.dotnet-tricks.com/Tutorial/mvc/TbR0041112-Asp.net-MVC-Request-Life-Cycle.html
所以我复制的图片,并添加我的评论就可以了,如下[礼遇:www.dotnet-tricks.com]

I started to read about the MVC5 life-cycle and found many articles on the net. one of them is the following link: http://www.dotnet-tricks.com/Tutorial/mvc/TbR0041112-Asp.net-MVC-Request-Life-Cycle.html so I copied the picture and added my comment on it as the following [courtesy: www.dotnet-tricks.com]

然后我在另一篇文章[在这里阅读: HTTP://www.$c $ cmag.com /条/ 1312081] ,如何将视图渲染字符串,返回的动作方法的返回类型。这样我可能能够使用延迟加载和渲染视图,同时还using语句中。

then I read in another article [ here: http://www.codemag.com/Article/1312081] , how to render the view to string and returned that as the return type of the action method. so that I may be able to use the lazy loading and render the view while still inside the using statement.

所以我所做的就是以下更改我的操作方法[说明是作为评论]

so all I did was the following change to my action method [ explanation is included as comments]

 // GET: /dept/
    public string  Index()
    {

        IView myView;
        string result;
        using (var ctx = new ApplicationDbContext())
        {
            //my model brought using the dbContext
            IEnumerable<department> d = ctx.departments;

            // now because I want to render the View here [forcibly] and not waiting
            //for the normal MVC pipeline to render my View I had to jump to the ViewEngine
            //and ask it to render my View [while i am still inside this using statement]
            // so referring to the excellent article on :http://www.codemag.com/Article/1312081
            //I did the following:
            ControllerContext.Controller.ViewData.Model = d;
            ViewEngineResult viewEngResult = ViewEngines.Engines.FindView(ControllerContext, "~/Views/dept/Index.cshtml", null);

            myView = viewEngResult.View;
            //till this point the View is not rendered yet
            StringWriter tw = new StringWriter();// used to render the View into string
            ViewContext vc = new ViewContext(ControllerContext, myView, ControllerContext.Controller.ViewData, ControllerContext.Controller.TempData, tw);
            //it is the following method .Render(viewContext, textWriter) that will start iterating on the IEnumerable<department> object
            myView.Render(vc, tw);

            result = tw.ToString();// the rendered View is now written as string to the result
            tw.Dispose();
        }

        return result;
    }
}

和我很高兴地看到,我的网页渲染成功没有那个著名的处置错误;看到的结果是:

and I was happy to see that my page rendered successfully without that famous disposing error; see the result:

所以总结起来:

在回答我的问题是:

当你从你的操作方法返回的ViewResult或ActionResult的;的观点依然没有呈现。一旦它在管道的视图引擎和视图引擎达到触发方法.Render(),它是在该时间的延迟加载对象将需要的DbContext和将导致的DbContext著名处置错误。
我还展示了如何可以使操作方法本身里面的视图。甚至的DbContext的使用语句中;我可以逃避处理错误。

when you return a ViewResult or ActionResult from your action method; the view is still not rendered. and once it reach in the pipeline to the ViewEngine and the ViewEngine trigger the method .Render(), it is at that time the lazy loading object will need the dbContext and will result in the famous Disposing error of the dbContext. I also showed how can you render the View inside the action method itself. and even inside the using statement of the dbContext; and I could escape that disposing error.

感谢您给大家:)

这篇关于懒加载的深刻理解和处理错误.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆