I’m trying to deep-load a EF object and keep it in cache for a certain period. In my case, I have an object (say User) and then an internal list of Books set as a virtual collection
public virtual ICollection<Books> ListOfBooks { get; set; }
Where there’s a foreign key relation between Books and User (and it all works fine)
I’m trying to deep-load this in a static central class
public static List<User> LoadAllBooksAndUsers() {
using (MyDB dc = new MyDB())
{
dc.Users.Include("ListOfBooks");
List<User> a = dc.Users.Where(l => l.Status == 1).ToList();
return a;
}
}
In my calling code, I have something like this:
var evx = DB.LoadAllBooksAndUsers();
var q = evx.Single(m=>m.name==name);
Examining evx in the debugger or q.ListOfBooks shows that the listOfBooks has an objects disposed exception and it is null.
And this is random – it seems to work once in a while and I don’t know under what condition.
I’m clueless as to what’s happening – my understanding is that using .Include() and then enumerating it will load all dependent foreign key objects, so why isn’t the method deep-loading all books into the user? What am I missing?
(I’d like to deep-load this object and cache it for a while as the data in it is used frequently)
You are using the
Includewrong. You need to use it together with the query building not in itself:You can find more info in this article about eager loading.