I'm using code first EF5 and I have an object which has a collection defined as virtual
(lazy loaded). This returns data when called. However I want it to be eager loaded. I've removed virtual
from the property signature but now it always returns null
data. EF doesn't even run the query, can anyone help?
Edit: I know about .include()
I'd just prefer to use the non-virtual property method of doing it.
Objects
User
([Key]
Id is on Resource object which is the Parent of person class):
namespace Entities
{
[Table("Users")]
public class User : Person
{
[Required]
public ICollection<Role> Roles { get; set; }
}
}
Role:
namespace Entities
{
public class Role
{
[Key]
public string Id { get; set; }
public virtual ICollection<User> Users { get; set; }
}
}
Lazy Loading vs. Eager Loading. While lazy loading delays the initialization of a resource, eager loading initializes or loads a resource as soon as the code is executed. Eager loading also involves pre-loading related entities referenced by a resource.
Eager loading is the process whereby a query for one type of entity also loads related entities as part of the query. Eager loading is achieved by use of the Include method. For example, the queries below will load blogs and all the posts related to each blog. Include is an extension method in the System.
Lazy loading in Entity Framework is the default phenomenon that happens for loading and accessing the related entities. However, eager loading is referred to the practice of force-loading all these relations.
Explicit loading means that the related data is explicitly loaded from the database at a later time. Lazy loading means that the related data is transparently loaded from the database when the navigation property is accessed.
This is a common confusion. The opposite of lazy loading is: no loading unless you explicitly do the loading yourself (e.g. by eager loading using Include
).
So if you turn off lazy loading in any way — removing the virtual
modifier is one of them — the behaviour does not turn into eager loading but no loading.
Think of it, suppose EF would eagerly load everything that is not marked for lazy loading. You run the risk of loading half the database by doing one simple query!
There is no way to make a navigation property eager loading by default (if you'd still want that after reading the above).
You will need to use the include method to force load of the ICollections within your entities with eager loading. The follwing link might help you: http://msdn.microsoft.com/en-us/data/jj574232.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With