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?