Question

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; } 
    }
}
Was it helpful?

Solution

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).

OTHER TIPS

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

Just one thing mention here.

If I turn off EF's LazyLoading with

this.DbContext.Configuration.LazyLoadingEnabled = false;

then, "include" method will not loading child entities for Eagerly loading.

so, if i want to use "include" in the query, I need to turn on EF's LazyLoading property at same time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top