Entity Framework Tip of the Day

Yesterday, I was doing so some work with EF and ran into something unusual - my navigational properties weren't being populated.

I rechecked my model and the DB schema and eerything was normal.

So it turns out that my entity object had just been inserted earlier in the procedure. This makes sense becuase EF usually does the navigational property population when you pull an entity directly from the DB.

So - either I find a solution or re-write my method to pull down the recently inserted entity again after insertion.

It turns out there is a single line of code that will fix everything:

Entities.Entry(item).Reference(c => c.NavgationProperty).Load();

This forces EF to load the property using the defined FK - and then using that navigational property works as expected. You'll have to do this for each property that needs to be populated.

Hope someone finds this useful.