为什么延迟加载在剃刀视图(cshtml文件)中不起作用? [英] Why lazy loading does not work in razor views (cshtml files)?

查看:62
本文介绍了为什么延迟加载在剃刀视图(cshtml文件)中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在cshtml文件中写了以下语句:-

I write following statements in my cshtml file:-

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

并获得异常Object reference null.

另一方面,在Controller.cs文件和即时窗口中也是如此.我知道这与延迟加载有关.

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.

它背后是否有任何概念,认为它在Cshtml文件的Expressions中不起作用?

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

谢谢

推荐答案

这不起作用,因为您的上下文在执行代码时就被释放了.所有数据都应加载到您的视图中,因此请关闭延迟加载并使用紧急加载.在结果上调用.Single()以强制加载和使用:例如,在context.Labels.Include(o => o.Parent)中从o强制加载.您还可以将这些结果展平到控制器中的视图模型中.

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.

这篇关于为什么延迟加载在剃刀视图(cshtml文件)中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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