6

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

bizon
  • 2,406
  • 2
  • 25
  • 28
  • Btw. don't use CTP5 there is already EF 4.1 RC which has "final" version of the API: http://www.microsoft.com/downloads/en/details.aspx?FamilyID=2dc5ddac-5a96-48b2-878d-b9f49d87569a – Ladislav Mrnka Mar 22 '11 at 08:48
  • How did you access `Address`. There should be lazy loading triggered. – Ladislav Mrnka Mar 22 '11 at 08:49
  • I have checked my versions. I have EntityFramework.dll runtime version v4.0.30319, and version 4.0.0.0. When I use nuget I get ' PM> Install-Package EntityFramework 'EntityFramework 4.1.10311.0' already installed. I-mo already has a reference to 'EntityFramework 4.1.10311.0'.' It is strange and lazy load still doesn't work. – bizon Mar 22 '11 at 09:44
  • 1
    Did you turn off lazy loading or proxy creation? – Ladislav Mrnka Mar 22 '11 at 09:47
  • Aaaa... I was sure that answer is not but in runtime it turned out that is true. I found somewhere that for tests I set LazyLoadingEnabled=false. Shame on me... Thank you very much for your time! – bizon Mar 22 '11 at 10:41

1 Answers1

5

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;
}
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
  • 1
    Or you can use more generic custom extension for includes: http://stackoverflow.com/questions/5376421/ef-including-other-entities-generic-repository-pattern/5376637#5376637 – Ladislav Mrnka Mar 22 '11 at 08:50