views:

34

answers:

2

I am pretty new to entity framework, but given a simple object like this:

public class Country
{
    public string Name { get; set; }

    [Key]
    public string Code { get; set; }

    public bool IsPostalCodeRequired { get; set; }

    public ICollection<Province> Provinces { get; set; }
}

returned by a DbContext, the Provinces property is null. If I use the Include method on my linq statement to include provinces, then it works. But I was wondering if there's a way to load them when I actually access the property? I know there's performance concerns to think about here, but I just want to know how to do it.

Thanks,

+1  A: 
  1. Make sure ObjectContext.ContextOptions.LazyLoadingEnabled is true. This is the default for a new project.
  2. If using pure POCO entities, lazy loading can't work (think about it). So you can use POCO proxies. Again, this is the default, but making lazy loading work with POCO proxies requires that all the relationship properties are declared virtual, and yours aren't.
Craig Stuntz
+1  A: 

Craig said it all. Just wanted to say by default ObjectContext has LazyLoading turned off . Although when you create new .net 4.0 project, the model designer explicitly turns it on for u for .net 4.0 projects. Its turned off because EF needs to preserver legacy behavior of .net 3.5 when lazy loading was not available. However as you may notice that you are using Dbcontext which is new and has no dependency to .net 3.5. Hence LazyLoading would be enabled by default to give you seamless experience.

zeeshanhirani
Thanks; clarified.
Craig Stuntz