从ASP.NET MVC视图返回时如何在对象上保留相关实体

时间:2021-07-31 09:46:30

I am working on an ASP.NET MVC RC2 app using Entity Framework.

我正在使用Entity Framework处理ASP.NET MVC RC2应用程序。

This is my Entity diagram.

这是我的实体图。

从ASP.NET MVC视图返回时如何在对象上保留相关实体

In my repository I get the entity like this:

在我的存储库中,我得到这样的实体:

public Product GetProduct(int id)
{
    return (from c in _entities.ProductSet.Include("User")
           where c.Id == id
           select c).FirstOrDefault();
}

My view:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<SampleApp.Models.Product>" %>

Edit product

<h2>Edit product</h2>

<%= Html.ValidationSummary("Edit was unsuccessful. Please correct the errors and try again.") %>

<% using (Html.BeginForm()) {%>

    <fieldset>
        <legend>Fields</legend>
        <p>
            <label for="Id">Id:</label>
            <%=  Model.Id %>
        </p>
        <p>
            <label for="Title">Title:</label>
            <%= Html.TextBox("Title", Model.Title) %>
            <%= Html.ValidationMessage("Title", "*") %>
        </p>
        <p>
            <label for="Body">Body:</label>
            <%= Html.TextBox("Body", Model.Body) %>
            <%= Html.ValidationMessage("Body", "*") %>
        </p>
        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>

<% } %>

<div>
    <%=Html.ActionLink("Back to List", "Index") %>
</div>

Problem and my question is: When the "Product" entity is returned from the view on post, the linked entity "User" is null. Why is that and is there any way to get around this?

问题和我的问题是:当从post上的视图返回“Product”实体时,链接的实体“User”为null。为什么这样,有没有办法解决这个问题?

从ASP.NET MVC视图返回时如何在对象上保留相关实体

2 个解决方案

#1


Because the productToEdit is a new product object populated from the form fields and if you don't have fields for the user how would you populate the User entity

因为productToEdit是从表单字段填充的新产品对象,如果您没有用户字段,您将如何填充用户实体

For a "workaround", first get the product from the db, edit this with the edited fields in the productToEdit and save to db

对于“变通方法”,首先从db获取产品,使用productToEdit中已编辑的字段对其进行编辑并保存到db

#2


You can also choose to use a custom ModelBinder that understands your model & persistence strategy to fully load the graph back into memory.

您还可以选择使用了解模型和持久性策略的自定义ModelBinder,将图形完全加载到内存中。

#1


Because the productToEdit is a new product object populated from the form fields and if you don't have fields for the user how would you populate the User entity

因为productToEdit是从表单字段填充的新产品对象,如果您没有用户字段,您将如何填充用户实体

For a "workaround", first get the product from the db, edit this with the edited fields in the productToEdit and save to db

对于“变通方法”,首先从db获取产品,使用productToEdit中已编辑的字段对其进行编辑并保存到db

#2


You can also choose to use a custom ModelBinder that understands your model & persistence strategy to fully load the graph back into memory.

您还可以选择使用了解模型和持久性策略的自定义ModelBinder,将图形完全加载到内存中。