I am using N-layer architecure in my project. In the data access layer I use Entity Framework code first.
When I fill an object in the DAL, dispose the context and transfer the object to the business layer, the navigation properties become null.
I have no problem if I don’t dispose the context, but my question is it good to dispose
the context?
If yes, how can I solve the problem when I transfer the object to the next layer (business), so that the navigational properties don’t become null.
My code in Data access layer:
public List<DomainObject.ContractCenter> GetAll()
{
try
{
List<ContractCenter> contractCenters = new List<ContractCenter>();
using (var context = new DBContext())
{
contractCenters = context.ContractCenters.ToList();
}
return contractCenters;
}
}
To answer your questions:
Yes, the context should be as short-lived as possible (see @khellang’s answer regarding UnitOfWork and IOC if you have a possibility to restructure your project and implement cleaner architecture).
You need to eager-load the related collections (navigational properties):