Search code examples
c#entity-framework

Entity Framework not loading related objects


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?


Solution

  • 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