Reputation: 21177
I'm trying to enable Lazy Loading on an EF4 context.
The code that is trying to load the data is:
using (IUnitOfWork uw = new EFUnitOfWork())
{
foreach (Document doc in uw.Documents.All)
{
Console.WriteLine("Name: {0} Description: {1} Category: {2}", doc.Name, doc.Description, doc.DocumentCategory.Name);
}
}
I am experimenting with the Repository and Unit Of Work patterns but as I understand it, the command below should work.
ctx.ContextOptions.LazyLoadingEnabled = true;
The problem I have is when accessing doc.DocumentCategory.Name, I get a NullReferenceException.
Why isn't this data being loaded lazily?
If I have DocumentCategories loaded, the DocumentCategory property is resolved.
My Document class is defined as follows:
public class Document
{
public Document()
{
}
public Document(int id)
{
Id = id;
}
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual string Description { get; set; }
public virtual int DocumentCategoryId { get; set; }
public virtual bool Deleted { get; set; }
public DocumentCategory DocumentCategory { get; set; }
public override string ToString()
{
return Name;
}
}
Upvotes: 1
Views: 396
Reputation: 3621
The DocumentCategory property also needs to be marked as virtual in order for lazy loading to be supported. Have a look at http://msdn.microsoft.com/en-us/library/dd468057.aspx
Upvotes: 3
Reputation: 4459
Is Document.DocumentCategory declared as virtual? EF requires this, to generate a proxy type, that will actually perform the lazy loading when you access the property. (Otherwise EF does not know, when you access the property's value)
Also, if DocumentCategory is already virtual, there might be other properties that prevend EF from generating a proxy-type. Inspect a "Document" instance with the debugger to see, whether it is actually a proxy-type.
Upvotes: 2