views:

56

answers:

1

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 following 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.

+2  A: 

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.

Mark Seemann
Marvellous. Went for option one which worked just fine. Thanks for that!
Phil.Wheeler
+1. Another option is to project onto a presentation model http://blogs.teamb.com/craigstuntz/2009/12/31/38500/
Craig Stuntz