0

My models:

public class Inventory
{
    public int ID { get; set; }
    public float Amount { get; set; }
    public ApplicationUser Owner { get; set; }
    public Item Item { get; set; }
    public Unit Unit { get; set; }
}
public class Unit
{
    public int ID { get; set; }
    public string Abbreviation { get; set; }
    public string FullName { get; set; }
    public UnitType Type { get; set; }
}

When passing all of my Inventorys in the controller to the view, the Unit field is always null in the view, regardless of what is in the database.

Action in controller that is being called:

public ActionResult Index()
{
    return View(db.Inventorys.ToList());
}

Relevant view parts:

@model IEnumerable<App.Models.Inventory>
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Amount)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Unit.Abbreviation)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })
        </td>
    </tr>
}

The second DisplayFor (item.Unit.Abbreviation) never shows anything. I put a breakpoint on the view and none of the models in Model have a value for the references to other models.

Database data (links to images because I don't have enough Rep):

Inventory

Units

I am using code first development.

1
  • Your current code for Index is only pointing to the FK. You have to explicitly load FK relations in the code. Please use faby's answer as given. Commented May 30, 2014 at 12:40

1 Answer 1

1

I think that the problem is that you aren't retrieving Unit records. if the schema of your database has foreign keys set correctly you can try this

public ActionResult Index()
{
    return View(db.Inventorys.Include(b => b.Unit_ID).ToList() );
}

refer this

Sign up to request clarification or add additional context in comments.

1 Comment

public virtual Unit Unit { ... } should do it as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.