Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework - Code First doesn't load referenced 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 Company in database I have Company (Id = 1 | name = "blah" | AddressId = 1) and its Address (Id = 1, Country = "Poland"). When I'm trying to load from my DbContext:

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

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

(I'm using CTP5.)

like image 373
bizon Avatar asked Mar 22 '11 00:03

bizon


1 Answers

try this:

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 entity as part of your Company entity.

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

Just for starters this is the implementation of Include() that Julia Lerman provides in "Programming Entity Framework" to support a unit-testable 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;
}
like image 142
BrokenGlass Avatar answered Nov 15 '22 11:11

BrokenGlass