c# - Entity Framework 中的一对一外键对性能有巨大影响吗?

标签 c# asp.net entity-framework

我会让这个变得非常简单。 我有两张 table 。

public class User
{
    public virtual int UserId { get; set; } //primary key AND foreign key
    //user attributes in here
    public virtual UserProfile UserProfile { get; set; }
}
public class UserProfile
{
    public virtual int UserId { get; set; } //primary key AND foreign key
    //profile attributes in here
    public virtual User User { get; set; }
}

基本上它们是两个表,它们以 1-1 的关系共享一个主键。这些是否应该合并为一个,我不知道,我是基于现有数据库。

现在,我遇到的问题是访问它的时间。

此代码运行速度很快(第二,也许是第二):

List<User> userList; //**This userList is defined elsewhere, but it's a list of about 400 users.
foreach (User user in userList)
{
    var test = user.FirstName;
}

这段代码真的很慢(10-30 秒):

List<User> userList; //**This userList is defined elsewhere, but it's a list of about 400 users.
foreach (User user in userList)
{
    var test = user.UserProfile.EmailAddress;
}

为什么当我从用户表访问 UserProfile 时,我的代码花费的时间这么长?!

最佳答案

可能是因为您在此处延迟加载 UserProfile。这意味着对于循环中的每次迭代,当您尝试访问电子邮件地址时,您都会单独调用数据库以加载 UserProfile

我不确定您是如何创建 userList 集合的,但是假设您正在对 User 表进行简单查询,您可以使用 Include 急切加载您希望预先拥有的任何属性:

var userList = (from u in dbContext.Users.Include("UserProfile")
                select u)

现在性能影响仅限于此查询最初执行时,枚举结果将不再需要单独调用数据库。

关于c# - Entity Framework 中的一对一外键对性能有巨大影响吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12322234/

相关文章:

c# - Entity Framework 和 SQL Server 临时表

c# - 如何在 OpenTK .NET Core 中设置 OpenGL API 版本?

c# - 在 IISExpress 中获取 ASP.Net Core 关闭触发 ApplicationStopping 事件

c# - 如何保护网页

c# - 网站不显示(说它下来),没有调用用户代码

c# - 如何配置 IIS/Asp.Net 以使用客户端证书与服务器进行 TLS 连接

c# - 生成 DDL 脚本以在 Entity Framework 中创建数据库

c# - LINQ 查询查找真实范围

c# - Visual C# 方法中 return 的问题

c# - 使用 MVVM 在 TreeView 中显示实体