Why is this referenced entity object null?
I have a strongly-typed view that receives a Design model for its rendering. My Design class (Entity) has a many-to-one relationship to a Designer (i.e. 1 Designer can have 1 or more Designs).
When trying to use the followi开发者_如何学Gong code, I get an NullReferenceException for the Design.Designer relationship. Obviously I'm doing something wrong, but being fairly inexperienced with the Entity Framework I need guidance on what it actually is.
<% foreach (var Design in Model)
{ %>
<figure>
<a href="View/<%= Design.ID %>" rel="Next" title="View this design">
<img id="design-<%= Design.ID %>"
src="/Templates/<%= Design.ID %>/preview.png"
height="200"
width="200"
alt="<%= Design.Title %> by <%= Design.Designer.DisplayName %>"
title="<%= Design.Title %> by <%= Design.Designer.DisplayName %>" />
</a>
</figure>
<%} %>
Any suggestions and pointers appreciated.
The Designer property is a so-called navigation property, and those are not loaded by default, which is why you get a NullReferenceException.
You have at least two options:
Include in query
When you query your ObjectContext, explicitly define that your query should include the Designer navigation property. This might look somewhat like this:
var q = from d in myObjectContext.Designs.Include("Designer")
select d;
Explicitly load the property before referencing it
You can also explicitly load the navigation property before referencing it. That would look like this:
foreach(var design in Model)
{
design.DesignerReference.Load();
// the rest of the code
}
However, this will cause EF to issue a query to the database for each element in the loop, so that would be a much chattier solution.
精彩评论