Why lazy loading does not work in razor views (cshtml files)?

一曲冷凌霜 提交于 2019-12-08 01:39:23

问题


I write following statements in my cshtml file:-

@{
string categoryName = string.Format("{0}->{1}", label.Category.Parent.Name,
label.Category.Name);
@categoryName
}

and get an exception Object reference null.

On the other hand the same works in the Controller.cs file and in the immediate window too. I know it is related to lazy loading.

Is there any concept behind it, that it does not work in Expressions in Cshtml files ?

Thanks


回答1:


This doesn't work because your context is disposed by the time your code is executed. All data should be loaded in your view so turn lazy loading off and use eager loading. Call .Single() on your results to force the load plus use: from o in context.Labels.Include(o=>o.Parent) for example to force the loading at that time. You could also flatten out these results into a view model in your controller.



来源:https://stackoverflow.com/questions/9441870/why-lazy-loading-does-not-work-in-razor-views-cshtml-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!