Asp.net mvc MVC 3-小部件在创建操作中很好,但在查看操作中有空值
我使用的是ASP.NETMVC3和实体框架 我有一个Asp.net mvc MVC 3-小部件在创建操作中很好,但在查看操作中有空值,asp.net-mvc,entity-framework,asp.net-mvc-3,model,Asp.net Mvc,Entity Framework,Asp.net Mvc 3,Model,我使用的是ASP.NETMVC3和实体框架 我有一个小部件控制器,带有标准的小部件CRUD操作 在我的创建操作中,我成功地创建了一个新的Widget对象,它有两个FooBar对象。这被添加到我的数据库中,操作重定向到视图操作 [HttpPost] public ActionResult Create(Widget model) { if (ModelState.IsValid) { //At this point, the widget has two FooBa
小部件
控制器,带有标准的小部件CRUD操作
在我的创建操作中,我成功地创建了一个新的Widget
对象,它有两个FooBar
对象。这被添加到我的数据库中,操作重定向到视图操作
[HttpPost]
public ActionResult Create(Widget model)
{
if (ModelState.IsValid)
{
//At this point, the widget has two FooBar properties. I can see the values for these FooBars just fine.
if (repo.AddWidget(model))
{
ViewBag.Message = "Your widget has been created.");
return RedirectToAction("View", new { id = model.Id });
}
else
{
ViewBag.Error = "Woops, something went wrong. Please try again.");
}
}
return View(model);
}
在查看操作中,我从我的存储库中获取新创建的小部件
——现在两个FooBar
属性为空
public ActionResult View(int id)
{
var widget = repo.GetWidget(id);
if (widget == null)
{
ViewBag.Error = "No widget found for the specified ID";
return RedirectToAction("Find");
}
//At this point, the widget has two null values for the FooBar1 and FooBar 2 properties
return View(widget);
}
在数据库本身中,我可以在我的小部件上看到正确的FooBar
ID值
我的模型的设置与本教程中显示的几乎完全相同:
公共类WidgetContext:DbContext
{
公共DbSet小部件{get;set;}
公共DbSet FooBars{get;set;}
}
有人能建议我如何开始追踪这个问题吗?
更新:
我应该澄清,无论何时调用视图操作,值都是空的,而不仅仅是在创建之后。看起来
FooBar
是单独的实体,FooBar1
和FooBar2
是导航属性。在这种情况下,您必须明确表示您希望加载它们(我们称之为急切加载):
注意:强类型包含要求EFv1或EFv4使用EF4.1:
var widget = context.Widgets
.Include("FooBar1")
.Include("FooBar2")
.SingleOfDefault(w => w.Id == id);
或创建自定义强类型扩展方法
或者您必须打开延迟加载。在视图中首次访问属性后,延迟加载会对数据库进行单独的查询。它需要使FooBar1
和FooBar2
虚拟,并且在呈现视图时上下文必须处于活动状态。通常这是由每个HTTP请求的单个上下文处理的,例如,在自定义控制器工厂或自定义HTTP模块中创建和处理上下文
下次请把你的问题填好。您已经显示了很多代码,但是缺少重要部分(
Windget
类和GetById
方法)。不幸的是,这里的用户不是预言家,所以我们现在需要了解必要的细节。这两种行动方法几乎与您的问题无关。嗨,拉迪斯拉夫-谢谢,这就是问题所在。通过使用Include
可以很好地加载对象。我仍然有点困惑,因为我的上下文已经开始了惰性加载——但至少现在我知道从哪里开始寻找了!啊,这一切都很顺利。我的POCO类需要一个构造函数,相关的对象需要声明为virtual
,然后一切都按预期工作!胡特:)
var widget = context.Widgets
.Include(w => w.FooBar1)
.Include(w => w.FooBar2)
.SingleOfDefault(w => w.Id == id);
var widget = context.Widgets
.Include("FooBar1")
.Include("FooBar2")
.SingleOfDefault(w => w.Id == id);