No nested results in Entity Framework Core [duplicate]

余生长醉 提交于 2019-12-01 11:38:51

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

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();

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.

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