问题
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