Monday, April 25, 2011

How to keep related entities on object when returned from ASP.NET MVC view

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

This is my Entity diagram.

Fi.1

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?

fig 2

From stackoverflow
  • 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

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

    jesperlind : I thought this was the case of the object "being new" coming from the view. I don't need to change the user in my scenario. The user is only in the relation to track who created the product. Thanks for this info, I will work around it.
  • You can also choose to use a custom ModelBinder that understands your model & persistence strategy to fully load the graph back into memory.

    jesperlind : Thanks that sounds promising, I'll look into that. I solved the above by problem attaching the original object in the Edit-function in the service. In this way it passes the same validation I got when I create a Product. (Product must have User)

0 comments:

Post a Comment