crayden
crayden

Reputation: 2270

How to render a related entity in Razor template

Using ASP.NET Core 2.0, Entity Framework Core, and Visual Studio, I am trying to use a @foreach loop in the razor view to render the List "SecondEntityList" within the Entity1 model. I was able to use Entity Framework Core to save data to the SQL Server local DB using another view and action method. The data was saved in both the dbo.Entity1 and dbo.Entity2 tables.

Visiting the razor view for listing the related entity list returns the following error:

NullReferenceException: Object reference not set to an instance of an object.

How can the @foreach loop be used to render the "SecondEntityList" within Entity1?

Entity 1

using System.Collections.Generic;

namespace Project.Models
{
    public class Entity1
    {
        public int Entity1Id { get; set; }
        public List<Entity2> SecondEntityList { get; set; }
    }
}

Entity 2

namespace Project.Models
{
    public class Entity2
    {
        public int Entity2Id { get; set; }
        public string Text { get; set; }

        public int Entity1Id { get; set; }
        public Entity1 Entity1 { get; set; }
    }
}

View Model

using System.Collections.Generic;
namespace Project.Models.ViewModels
{
    public class MyViewModel
    {
        public Entity1 Entity1 = new Entity1();
        public IEnumerable<Project.Models.Entity2> Entity2List;
    }
}

Action Method

[HttpGet]
public IActionResult MyListView(long key, MyViewModel mvm)
{
    mvm.Entity1 = context.Entity1.Single(i => i.Entity1Id == key);
    mvm.Entity2List = mvm.Entity1.SecondEntityList;
    return View(mvm);
}

Razor View

@model Sediment.Models.ViewModels.MyViewModel;
@foreach (Project.Models.Entity2 i in Model.Entity2List)
{
    @i.Text
}

Upvotes: 0

Views: 463

Answers (1)

cwharris
cwharris

Reputation: 18125

Using entity models in your views is bad practice, for a number of reasons. There is, however, a way to do what you’re asking by using .Include(...) in your query.

mvm.Entity1 =
    context.Entity1
        .Include(i => i.SecondEntityList)
        .Single(i => i.Entity1Id == key);

If this is a serious project and you expect to keep this code around for a while, I highly suggest you separate your view concerns from your database. Otherwise you may end up trying to execute a query in your razor view after the db context has been disposed. Among a host of other bugs you could encounter.

Upvotes: 1

Related Questions