entity framework - getting null exception using foreign key

Posted by Nick on Stack Overflow See other posts from Stack Overflow or by Nick
Published on 2010-03-27T17:05:57Z Indexed on 2010/03/27 17:13 UTC
Read the original article Hit count: 329

Filed under:
|
|
|

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

-Users -Comments

There is a one-to-many relationship set up for this; there is a foreign key from Comments.CommentorID to Users.UserID. When I do the LINQ query and try to bind to a DataList, 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;
        dl_MajorComments.DataBind();

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):

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

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

Thanks, Nick

© Stack Overflow or respective owner

Related posts about entity

Related posts about framework