Search code examples
c#linqentity-frameworkobjectquery

ObjectContext Closed error when using Include?


I am trying to create a generic Get method for Entity Framework, with a dynamic Where and Include. I am using the code below, however when I try to access a Navigation Property that was in the Include list, I am getting an error about the Object Context being closed

Isn't .Include() supposed to load those objects so I don't need to keep the ObjectContext open?

public static List<T> GetList<T>(Func<T, bool> where, string[] includes)
    where T : EntityObject
{
    using (var context = new TContext())
    {
        ObjectQuery<T> q = context.CreateObjectSet<T>();
        foreach (string navProperty in includes)
        {
            q.Include(navProperty);
        }

        return q.Where<T>(where).ToList();
    }
}

Code causing error:

var x = DAL<MyContext>.GetList<MyEntity>(
                p => p.Id == 1
                , new string[]{ "Type" } );

var y = x.Type;  // Throws an error that context has been closed

I feel I must be making some kind of stupid mistake here because I'm new to EF and am still trying to figure it out.


Solution

  • You are not re-assigning q - this should fix it:

        foreach (string navProperty in includes)
        {
            q = q.Include(navProperty);
        }
    

    Remember you are using extension methods that each return a new IQueryable<T>, not modifying the original.