I am using Entity Framework 5, MVC 4. My User has these relations:

User-Profile: 1 to 1 relationship. (one user has one profile)

User-Posts: 1 to many relationship. (one user has many post)

User-Roles: many to many relationship (one user has many roles, a role might be assign to many users)

My question is how Lazy Loading works according to each type of these relations, and how "deep"? When I get a User from Context, what will be loaded?

Any help would be appreciated!

有帮助吗?

解决方案

The idea behind lazy loading is that the entity framework loads only the information that you have attempted to access. Consider the following:

using (MyContext context = new MyContext())
{
    User myUser = context.Users.First();
}

In this example, only the User object is loaded. None of the related entities are retrieved from the database until they are first accessed.

using (MyContext context = new MyContext())
{
    User myUser = context.Users.First();   // User is loaded from database

    Profile myProfile = myUser.Profile;    // Associated profile is loaded
}

In the second example, there are two database calls - one to load the User, and a second to load the Profile when it is first accessed.

All three types of relationships (one-to-one, one-to-many, many-to-many) have this same behavior: related objects are not loaded until first access.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top