No nested results in Entity Framework Core

asp.net-core c# entity-framework-core

Question

i have a strange behavior in C# with EF It's a .NET Core project with EF Core 1.1.0

"Microsoft.EntityFrameworkCore.SqlServer": "1.1.0",
"Microsoft.EntityFrameworkCore.Tools": "1.1.0-preview4-final",

I've created two Models, "User" and "Group"

 public class User
 {
    public int Id { get; set; }
    public string name { get; set; }
    public string lastName { get; set; }

    public List<Group> Groups { get; set; }
 }

 public class Group
 {
    public int Id { get; set; }
    public string groupName { get; set; }
    public virtual User User { get; set; }
 }

The result schould give me a User with a list of his groups.

Now the strange part:

Result comes back from DB, i look into allUser, Groups are Null

I take a look into the context to see the Groups

Groups are filled:

Groups are filled

Now i look again into allUser Result and magically the Group is filled inside every User item.

Groups are filled inside User:

Groups are filled inside User

I really appreciate any help!!

1
2
3/4/2017 2:00:12 PM

Accepted Answer

Looks like you are lazy loading the entities.

You can eager load them by using .Include.

 var allUsers = context.Users.Include(user => user.Groups).ToList();

This approach loads the first entity (Users) as well as the related entities as part of the query (Groups).

6
3/4/2017 2:09:17 PM

Popular Answer

This behavior comes from the laziness of loading entities.

By default, you have to manually load each of sub-entity. It is called eager-loading.

In order to eager-load your entities, you have to use the .Include() method on each of your navigation properties.

e.g. context.User.Include(x => x.Groups)

The Include method generates a new SQL statement to retrieve your Groups from database.

Then you can use the ToList() method to force executing your query.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow