I'm having trouble using EF Code first 4.1 and am probably not understanding something.
My understanding is that by marking relationships (whether collections or single objects) as virtual, they will be lazy loaded on demand, so I could do something like:
var page = context.Pages.Where(xxxx);
var department = page.Department; //load this on demand?
var name = department.Name; //null reference exception
page.DepartmentId is populated correctly, however. In addition, manual loading the reference with context.Entry(page).Reference(p => p.Department).Load() works, but the whole point of having an object model is to not have to obsessively do that everywhere.
public class Page
{
public int DepartmentId { get; set; }
public virtual Department { get; set; }
}
public class Department
{
public virtual ICollection<Page> Pages { get; set; }
}
context OnModelCreating
modelBuilder.Entity<Page>().HasRequired(x => x.Department).WithMany(y => y.Pages).HasForeignKey(x => x.DepartmentId).WillCascadeOnDelete(false);
I've not disabled lazy loading, of course.
I figured out what was wrong in my situation. I marked the default constructor as private so ef was not generating the proxies for me.
thanks everyone.