Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 337
Craig Avatar asked Aug 19 '12 08:08

Craig


People also ask

How do you load related entities in EF?

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.

What is the way of loading data in Entity Framework?

Entity Framework supports three ways to load related data - eager loading, lazy loading and explicit loading.

What are different types of loading available to load related entities in EF?

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.

How do I enable eager loading in Entity Framework?

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.


1 Answers

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

like image 98
fra Avatar answered Oct 06 '22 02:10

fra