Laurens
Laurens

Reputation: 2088

Entity Framework: accessing associations

My domain model with associations is as follows:

Depending on the state of a User, I need to update a field in the project. My query is as follows:

var projects = from project in _data.projects
               join task in _data.tasks on project.ProjectID equals task.ProjectID
               join user in _data.usersactive on task.TaskID equals user.TaskID
               where user.Active == false
               select project;

This allows me to get the projects that have users that are inactive.

foreach (Project project in projects)
{
    bool needUpdate = false;

    foreach (Task task in project.tasks)
    {
        foreach (User user in task.users)
        {
            // Depending on state of user
            // needUpdate = true;
        }
    }

    // If needUpdate = true
    // Do something
}

Obviously this code is going to get me:

There is already an open DataReader associated with this Connection which must be closed first.

I am on MySQL however, and as such am not able to simply leverage MultipleActiveResultSets=True.

How would I be able to eagerly load these associations and have them accessible in the foreach loop?

Upvotes: 0

Views: 75

Answers (1)

gideon
gideon

Reputation: 19465

To eagerly load a linq set:

var projects = (from project in _data.projects
               join task in 
                       _data.tasks on project.ProjectID equals task.ProjectID
               join user in 
                       _data.usersactive on task.TaskID equals user.TaskID
               where user.Active == false
               select project).ToList();

Upvotes: 1

Related Questions