No nested results in Entity Framework Core [duplicate]

隐身守侯 提交于 2019-12-19 10:18:12

问题


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:

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

Groups are filled inside User:

I really appreciate any help!!


回答1:


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




回答2:


It's not magic the DbContext won't download entities from the DB until you not tirgger that. When you clicked on the context.Groups Results View in debugging, the DbContext gets all the Groups from the DB so after that it can associate to the users.

I think you are searching for the Include method where you can get the users with the associated groups in one query like this:

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



回答3:


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.



来源:https://stackoverflow.com/questions/42596608/no-nested-results-in-entity-framework-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!