Entity Framework - Code First does not load reference object

I have two simple classes generated by code first.

public class Company { public int Id { get; set; } public string Name { get; set; } public virtual Address Address { get; set; } } public class Address { public int Id { get; set; } public string Country { get; set; } ... } 

After saving the company in the database, I have the Company (Id = 1 | name = "blah" | AddressId = 1) and its Address (Id = 1, Country = "Poland"). When I try to load from my DbContext:

 Company company = context.Companies.Find(id); 

I get a company with a null Address property. What am I doing wrong?

(I am using CTP5.)

+6
entity-framework-4 ef-code-first code-first
source share
1 answer

try the following:

 Company company = context.Companies.Include("Address").Find(id); 

or with the new typed syntax:

 Company company = context.Companies.Include(c => c.Address).Find(id); 

This tells EF to eagerly load the Address object as part of your Company object.

It also seems that you have a repository layer on top of EF - make sure your repository implementation supports Include() , if this is the case.

For starters only, this is the Include() implementation that Julia Lerman provides in the Entity Framework Program to support the tested repository pattern with POCOS (this version only works with the first syntax):

 public static IQueryable<TSource> Include<TSource>(this IQueryable<TSource> source, string path) { var objectQuery = source as ObjectQuery<TSource>; if (objectQuery != null) { return objectQuery.Include(path); } return source; } 
+5
source share

All Articles