Majid
Majid

Reputation: 14253

ObjectContext disposed also in opened context of EF

I have this method for creating DataTable:

private DataTable toDataTable<T>(IEnumerable<T> items)
    {
        var tb = new DataTable(typeof(T).Name);
        using (var context = new MyEntity())
        {
            PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (var prop in props)
            {
                tb.Columns.Add(prop.Name, prop.PropertyType);
            }

            foreach (var item in items)
            {
                var values = new object[props.Length];
                for (var i = 0; i < props.Length; i++)
                {
                    values[i] = props[i].GetValue(item, null);
                }

                tb.Rows.Add(values);
            }
        }
       return tb;

    }

but it give me this error in second foreach:

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

since I opened my EF's context;why again this error occurs?

Upvotes: 0

Views: 154

Answers (3)

Joe Enos
Joe Enos

Reputation: 40393

I'm assuming the items collection contains entities from EF. Those items originally belonged to an ObjectContext, which apparently was closed before you passed them into this method. Opening a brand new context doesn't help because that's not the context that these items belong to.

When you use reflection on one of these entities, it's likely attempting to lazily access a navigation property of the entity, which would require a database trip, but since the context that the entity belongs to is gone, that database trip cannot happen.

You can reattach the item to the new context, then this should work:

foreach (var item in items)
{
    context.Attach(item);
    ... // now your item is attached to a live context again, and it
        // can hit the database
}

This is assuming you want to lazily load this - if you want to eagerly load and avoid the second database hit, you'd need to Include it when you retrieve the item from the database in the first place.

Upvotes: 1

STW
STW

Reputation: 46366

If items originates from EntityFramework as well then it may be the culprit--it's Context may have closed.

Do you know which line the exception originates from?

Upvotes: 1

Keith Payne
Keith Payne

Reputation: 3082

The IEnumerable<T> that you are passing into toDataTable<T>() has not been realized yet. The context of items is already disposed. You have forgotten a ToList() in the calling code.

Upvotes: 3

Related Questions