Lazy loading using Entity Framework

entity entity-framework

Question

using(DataContext db = new DataContext ())
{
    var result = db.SomeTable.ToList();
    return result;
}

The issue is that after I return the result, the connection is cut off, and as a consequence, if I attempt to access any of the child components, it crashes. This occurs because the child relations are never loaded prior to usage when lazy loading is set to True (the default) and I only utilize them after the connection has been terminated. So what is the best course of action for this?

I attempted to disable the lazy loading, however none of the child relation tables loaded as a result.

1
8
11/3/2011 2:44:00 AM

Accepted Answer

Your child collections may always be loaded explicitly:

var result = db.SomeTable.Include("SomeChildCollectionName")
                         .Include("AnotherChildCollectionName")
                         .ToList();
14
1/10/2011 2:42:00 PM

Popular Answer

The.include() function may be used.

var result = db.SomeTable.Include("ChildEntitySet").ToList();

You might include aresult.ChildEntitySet.Load() Call before coming back. This will need two visits to the server, which makes it less efficient. The.Include() function creates a SQL Statement with a JOIN that only requires one server visit.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow