4

I am using entity framework code first and I want to mark a collection for use no lazy loading. I dont know this concept are called as eager loading. But so far I know I just have to set virtual attribute for using lazy loading. But if I dont want lazy loading, I should just leave it no virtual.

public class User
{
    public int Id { get; set; }
    public string Username { get; set; }

    public ICollection<Role> Roles { get; set; } // no virtual
}

public class Role
{
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<User> Users { get; set; } // virtual
}

In my conceptual model I always will need the Roles for the User, then I dont want lazy loading. And I dont want use Include() in my query. I just want that attribute always available.

    using (DataContext ctx = new DataContext(connectionString))
    {
        var role = ctx.Roles.Find(1);
        var users = role.Users; //lazy loading working            

        var user = ctx.Users.Find(1);

        var roles = user.Roles; //null exception
    }

But, I when I load the an User, Entity Framework give me the Roles attribute as null. Also, When I load a Role, the Users attribute works well, with lazy loading.

If I use Include, I can get it working, but I dont want use it. Also because I can't use the Find method.

var user = ctx.Users.Include(r => r.Roles).Find(1); //the find method is not accessible
var user = ctx.Users.Include(r => r.Roles).First(u => Id == 1); //I must use this way

So, I am thinking the wrong way? Entity Framework assumes by default we alaways have to use Include to dont use lazy loading? Or I am missing some thing to get it working?

iuristona
  • 927
  • 13
  • 30
  • 1
    possible duplicate of [Entity framework auto eager load](http://stackoverflow.com/questions/5001311/entity-framework-auto-eager-load) and http://stackoverflow.com/questions/5955544/forcing-eager-loading-for-a-navigation-property – Slauma Aug 06 '12 at 19:29

1 Answers1

4

You could load the collection afterwards as well:

// Find the User entity with the given primary key value == 1
var user = ctx.Users.Find(1); 

// Loads the related Roles entities associated with the User entity
ctx.Entry(user).Collection(u => u.Roles).Load();
EricSchaefer
  • 25,272
  • 21
  • 67
  • 103
Mark Oreta
  • 10,346
  • 1
  • 33
  • 36