简体   繁体   中英

Calling a model within a model in a view. (asp.net MVC)

Bare in mind, I'm quite new to ASP.NET MVC. So using EF code first method, I created 2 models, Movie and Producer:

public class Movie {
    public int ID {get;set;}
    public string Name {get;set;}
    public string Genre {get;set;}
    public Producer Producer {get;set;}
}
public class Producer {
    public int ID {get;set;}
    public string Name {get;set;}
    public DateTime DOB {get;set;}
    public List<Movie> Movies {get;set;}
}

And in the controller class "Movies", I called a view:

public class MoviesController : Controller
{
//context just has DbSet< .. > of both classes.
MoviesContext db = new MoviesContext();
    public ActionResult Index()
    {
        var movies = from m in db.Movies
                     select m;
        return View(movies.ToList());
    }
}

But if I call the producer within the view

@foreach(var item in Model)
{
    <p>@item.Producer.Name</p>
}

MVC crashes with "Object reference not set to an instance of an object." error, even though when I look at the database, the Producer_ID field (which Code first made) was filled in and all of the producers with the according ID's exist in the database as well.

I did put the values inside the database manually, is that what would be causing it?

Any kind of help is more than appreciated! :)

Try loading Producer data explicitly, by calling function Include()

public ActionResult Index()
{
    var movies = from m in db.Movies.Include(b => b.Producer) 
                 select m;
    return View(movies.ToList());
}

If lazy loading is enabled, your property Producer would be loaded first time it is needed. However, if lazy loading is disabled, you need to explicitly specify that you want to load other related entities.

The method Include that accepts a lambda is an extension method, so you will need to add this using at the top of your file:

using System.Data.Entity;

Alternative is to specify include by using string:

public ActionResult Index()
{
    var movies = from m in db.Movies.Include("Producer") 
                 select m;
    return View(movies.ToList());
}

The result is the same, but first approach does not contain "magic strings", which is often preferable.

This is wrong, just put a break point before the return and check if the movies.Producer is not null, i beat yes.. You need to Include producer like this:

  var movies = from m in db.Movies.Include(m => m.Producer) 

Or maybe do a join with Producer table, see a 3 table join example (in your case is just 2) here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM