ASP.Net MVC 3,复杂对象和延迟加载 [英] ASP.Net MVC 3, Complex Objects and Lazy Loading

查看:282
本文介绍了ASP.Net MVC 3,复杂对象和延迟加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我是新来的ASP.Net MVC 3,和我也使用EF 4.1。

First of all, I am new to ASP.Net MVC 3, and I am also using EF 4.1.

我有一个复杂的对象,类似的事情让我们说包含类别对象的产品对象。因此,我们有Product.CategoryId,Product.Category和一些额外的属性。我也有一个窗体创建产品下拉列表选择类别。

I have a complex object, something similar to let's say a Product object containing a Category object. So we have Product.CategoryId, Product.Category and some extra properties. I also have a form to create products with a dropdown list to select the category.

在我的控制器,该产品已被创建后,我需要有访问类别的某些属性进行一些额外的东西。然而,尽管Product.CategoryId设置,我不能因为Product.Category为null访问Product.Category.SomeProperty。我预计Product.Category会自动使用一些延迟加载加载,但它似乎并不如此。

In my controller, after the product has been created, I need to have access to some property of the Category to perform some extra stuff. However, although Product.CategoryId is set, I cannot access Product.Category.SomeProperty because Product.Category is null. I expected Product.Category would be loaded automatically using some lazy loading, but it does not seem to be.

在我的控制器code是这样的:

The code in my Controller looks like this:

[HttpPost]
public ActionResult Create(Product product)
{
   if (ModelState.IsValid)
    {
        db.Products.Add(product);
        db.SaveChanges();

        string someString = product.Category.SomeProperty;
        ...

现在,这并不工作,因为product.Category为空。我需要什么补充,这样我可以访问SomeProperty?

Now, this does not work because product.Category is null. What do I need to add so that I can access SomeProperty?

推荐答案

由于要添加一个新的对象延迟加载不会在这种情况下工作。延迟加载将工作由EF上下文中创建的代理服务器的实体。

Lazy loading will not work in this scenario because you are adding a new object. Lazy loading will work on "Proxy" entities created by EF context.

所以,你可以在这里做的是<一个href=\"http://blogs.msdn.com/b/adonet/archive/2011/01/31/using-dbcontext-in-ef-feature-ctp5-part-6-loading-related-entities.aspx\">explicitly加载导航属性。

So what you can do here is explicitly load the navigational property.

    db.Products.Add(product);
    db.SaveChanges();

    db.Entry(product).Reference(p => p.Category).Load();

    string someString = product.Category.SomeProperty;

这篇关于ASP.Net MVC 3,复杂对象和延迟加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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