I am new to the Entity Framework 4. I’ve done a bit of playing around with SQL Server, and MySQL. I ran into a problem using MySQL in regards to lazy loading, and I believe is that the MySQL connector doesn’t allow multiple queries on the same connection – it must be closed first.
I would like to run a query, store a reference to the results in a field of my class, and then later on, modify/save it or load related data. However, the context has gone out of scope and been disposed of.
class MyClass {
List<AThing> _stuff;
private void ReadStuff() {
using (var context = new MyEntities()) {
_stuff = context.TableOfStuff.ToList();
}
}
// Stuff is used by other methods, bound to controls, etc.
}
So, does Stuff exist without a context? From what I understand, the context is what does change tracking and the like… Once ToList() is called, my context is useless for another query.
Must I avoid this? Is there a better way of accomplishing this? Am I wrong above?
Your code is fine. When
contextgoes out of scope the items in the list are no longer attached. If you change them you canAttachthem to a new context. But there are other ways depening on what you want to do and how you want to do it.Calling
ToListmaterializes your query but won’t leave an openDataReader. So you should be able to execute multiple queries.