1

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.

Rachel
  • 130,264
  • 66
  • 304
  • 490

1 Answers1

3

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.

BrokenGlass
  • 158,293
  • 28
  • 286
  • 335