Entity Framework Core 中没有嵌套结果 [英] No nested results in Entity Framework Core
问题描述
我在 C# 中使用 EF 有一个奇怪的行为这是一个带有 EF Core 1.1.0 的 .NET Core 项目
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.
现在是奇怪的部分:
结果从数据库返回,我查看所有用户,组为空
Result comes back from DB, i look into allUser, Groups are Null
我查看上下文以查看组
组已满:
现在我再次查看 allUser Result 并且神奇地该组填充在每个用户项中.
Now i look again into allUser Result and magically the Group is filled inside every User item.
组在用户内部填充:
我非常感谢您的帮助!!
I really appreciate any help!!
推荐答案
看起来您在延迟加载实体.
Looks like you are lazy loading the entities.
您可以使用 .Include
预先加载它们.
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).
这篇关于Entity Framework Core 中没有嵌套结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!