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开发者_StackOverflow 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?
The problem is that movieList.Genre
is null, and you can't access the Name
property of a null
object.
You can solve this by writing <%= Html.Encode(movieList.Genre == null ? String.Empty : movieList.Genre.Name) %>
.
If you don't want your views to be so verbose, you could add a GenreName
property to the Movie
entity class and move the null check there.
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
}
精彩评论