Entity Framework not loading related objects

c# entity-framework

Question

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?

1
6
8/19/2012 8:39:07 AM

Accepted Answer

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

5
8/19/2012 8:44:34 AM

Popular Answer

What you are looking for is .Include you use it like this

var recordWithParentAttached = db.Tasks.Include(o => o.Person).Single(o => o.person_id == personId);

with .Include your parents (or related records) will get attached and passed across while without they will be nulls.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow