Search code examples
asp.netasp.net-mvcentity-frameworkentity-relationship

Entity Framework - joining nulls - NullReferenceException was unhandled by user code


I am writing an asp.net mvc application to learn Entity Framework with and am running into an issue that I do not know how to handle. For simplicity lets take the following table structure:

Movie  
ID (int, not null, auto increment)  
Name (varchar)  
GenreID (int)

and

Genre  
ID (int, not null, auto increment)  
Name (varchar)

Movie.GenreID is a FK reference to Genre.ID

I have brought across all of the tables using the visual designer in VS 2008 and tried the following Linq query:

IEnumerable<Movie> movieList = from f in dataContext.MovieSet.Include("Genre").ToList();

I can output the data in a view using:

<%= Html.Encode( movieList.Genre.Name ) %>

Everything works just fine until I have an item in the Movie table with a null GenreID. Is there something I can do to this query to make it still be able to output (just leave it blank when applicable) or am I doing something horribly wrong?


Solution

  • This is probably much more readable than .Include("")

    from f in dataContext.MovieSet
    select new
        {
           Name = f.Name,
           Genre = f.Genre // This effectively performs a join.
           ...
        }
    

    You can also check for the problem that way:

    from f in dataContext.MovieSet
    select new
        {
           Name = f.Name,
           GenreName = f.Genre == null ? "" : f.Genre.Name
           ...
        }
    

    This gives you more flexibility, for instance:

    from f in dataContext.Genres
    select new
        {
            Name = f.Name
            Movies = from movie in f.Movies
                     where movie.Duration > 240
                     select movied
        }