I am using EF with Repository Pattern and unit of Work. I am pulling an object Person with inner object Employment.
The following is how the classes are constructed:
class Person
{
Employment employments;
}
class Employment
{
int ID {get;set;}
string Employer {get;set;}
}
Lazy Loading is enabled.
The following is how i’m getting the Person Object:
Person p;
using (unitOfWork = new UnitOfWork())
{
p=unitOfWork.PersonRep.Single(s => s.Id== Id);
}
return p;
Outside this code p.employments is not accessible. What’s the best practice for this architecture? And why is the navigation property not persisting?
The reason your navigation property is causing errors is because you’re disposing of the context, prior to the navigation property being loaded.
If you think about what’s happening:
You either need to eagerly load the Employer for your person using include, from your context it would be something like
context.Persons.Include(p => p.employments)it’s hard to tell because you don’t have that code posted.Or, keep your database connection alive longer. Accessing the employer information for the person, seems like it would all be handled in the same unit, so maybe you should consider keeping your unit of work alive throughout your entire method.