Nick Nick - 1 year ago 149
C# Question

entity framework - getting null exception using foreign key

Having some trouble with what should be a very simple scenario. For example purposes, I have two tables:


There is a one-to-many relationship set up for this; there is a foreign key from

. When I do the LINQ query and try to bind to a
, I get a null exception. Here is the code:

FKMModel.FKMEntities ctx = new FKMModel.FKMEntities();
IQueryable<Comment> CommentQuery =
from x in ctx.Comment
where x.SiteID == 101
select x;
List<Comment> Comments = CommentQuery.ToList();
dl_MajorComments.DataSource = Comments;

In the ASPX page, I have the following as an ItemTemplate (I simplified it and took out the styling, etc, for purposes of posting here since it's irrelevant):

<%# ((FKMModel.Comment)Container.DataItem).FKMUser.Username %>
<%# ((FKMModel.Comment)Container.DataItem).CommentDate.Value.ToShortDateString() %>
<%# ((FKMModel.Comment)Container.DataItem).CommentTime %>

The exception occurs on the first binding (
). Since the foreign key is set up, I should have no problem accessing any properties from the Users table. Intellisense set up the
navigation property and it knows the properties of that foreign table. What is going on here???

Answer Source

You might need to add the "Include" statement in your query, or disable lazy loading - there's some examples in the following question/.answers:

In your example, you'd want to add the Include as follows:

IQueryable<Comment> CommentQuery =
            from x in ctx.Comment
            .Include("<name of FK navigation property">)
            where x.SiteID == 101 
            select x;

Or you can explicitly disable lazy loading for the context - depends on your design as it can be an expensive exercise to do complete object graph loads. I wrote a blog post a while back which addresses some of the "fun" of FKs in EF v1.

Also, you can explicitly ensure the FK (Navigation Property) is loaded by specifically loading it, say on Data Bind.

if (!<entity>.<navigation property>.IsLoaded)   //Ensure the relationship has loaded 
        <entity>.<navigation property>.Load();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download