Paul
Paul

Reputation: 15

Entity Framework query: access foreign key (navigation) data from record

I'm new to EF and I have two tables, the first called ContestEntry and the second Items which has a one to many relationship with ContestEntry. I'm trying to access Contest Entries and then from there get the related Item information. Here is the code I'm using.

ContestEntry cEntry =
        Ctx.ContestEntries.Include("Item").Where(ce => ce.ID == 4).First();

The problem is that the Item relationship is NULL when I look at it in the debugger.

I'm probably missing something just not sure. Any help would be appreciated.

Thank You!

Upvotes: 0

Views: 1500

Answers (1)

marc_s
marc_s

Reputation: 754963

In your question, you mention the seconds table is "Items", yet in your LINQ query, you're including "Item" - just a typo??

Also, another way to load a referenced entity would be this:

ContestEntry cEntry =
    Ctx.ContestEntries.Include("Item").Where(ce => ce.ID == 4).First();

if(!cEntry.Items.IsLoaded)
{
   cEntry.Items.Load();
}

If you have a 1:n navigational property, you should be able to check whether it's been loaded, and if not, load it on demand when you need it.

Marc

Upvotes: 3

Related Questions