I am new to Entity Framework, but might be misunderstanding something, or doing something wrong.
My code, to get me a list of tasks for a particular person :
public List<TaskObject> GetAssignedTasks(int personId)
{
var items = (from s in _te.tasks where s.person.person_id == personId select s).ToList();
var tasks = new List<TaskObject>();
foreach (var t in items)
{
TaskObject tk = Transformer.UnpackTask(t);
tasks.Add(tk);
}
return tasks;
}
My problem is, it seems to get a list of records back, but related items are not loaded. My 'Transformer.UnpackTask' method takes the task entity which I loaded, and then transforms it into a different object which goes up to the UI via the business/service layers.
But as soon as my Unpacker function tries to references an item which is a related object (For example, a task has an 'AssignedPerson', which has a Person entity with person details. But the AssignedPerson property of my entity is NULL. I thought it would load the related items.
Am I misunderstanding?
Entity Framework supports the following three methods to load related data. In Eager Loading, all relevant data for an entity is loaded at the time of the query of the entity in the context object. Eager Loading can be done by using the "Include" method. To perform Eager Loading, Lazy Loading must be disabled.
Entity Framework supports three ways to load related data - eager loading, lazy loading and explicit loading.
Explicit loading means that the related data is explicitly loaded from the database at a later time. Lazy loading means that the related data is transparently loaded from the database when the navigation property is accessed.
Entity Framework : A Comprehensive Course Eager loading is the process whereby a query for one type of entity also loads related entities as part of the query. Eager loading is achieved by the use of the Include method. It means that requesting related data be returned along with query results from the database.
You should explicitly include references with the Include() method. It has two overloads: one takes the property as lambda expression, the other takes the path to load as a string (useful when you need to load references on objects available in collections).
MSDN reference
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With