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.)
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With