This one i had today is a strange one.
I have this query in an assembly method.
public Order[] SelectAllOrders()
{
Order[] orders;
using (MyDataContext context = new MyDataContext())
{
DataLoadOptions dlo = new DataLoadOptions();
dlo.LoadWith<Order>(order => order.OrderDetails);
context.LoadOptions = dlo;
orders = context.Orders.Select(p => p).ToArray();
}
return orders;
}
Supposed i already called the ToArray() the SQL Command executed and gave me the objects i need and i give them to a new Order[] array this should not need the DataContext instance.
While im serializing the Order[] i get from the method return, serializer tries to access the DataContext again and i get an exception that cannot access disposed object.
Tried without the using() statement and works like it should. But, why i get this behavior?
Anyone could give an explanation why deferred loading still remains while I’m calling .ToArray() and assigning new variable with the contents?
The
Select(p=>p)achieves very little; you might as well just call:Re the problem – I would guess that either
OrderDetailshasn’t really loaded, or it is trying to load some other data lazily. I would suggest investigating by (in a dev session):With this, you should be able to see any extra database trips that are happning after the
ToArraybut before theDispose(). The point being: this data is needed for serialization, so either a: ensure it gets loaded, or b: exclude it from serialization.