实体框架中的一对一外键带来巨大的性能?

pro*_*don 3 c# asp.net entity-framework

我将使这真的很简单.我有两张桌子.

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; }
}
Run Code Online (Sandbox Code Playgroud)

基本上它们是两个共享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;
}
Run Code Online (Sandbox Code Playgroud)

这个代码真的很慢(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;
}
Run Code Online (Sandbox Code Playgroud)

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

mcl*_*129 10

可能是因为你在UserProfile这里懒得加载.这意味着,对于循环中的每次迭代,UserProfile当您尝试访问电子邮件地址时,您将单独调用要加载的数据库.

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

var userList = (from u in dbContext.Users.Include("UserProfile")
                select u)
Run Code Online (Sandbox Code Playgroud)

现在,性能命中仅限于此查询被初始执行时,枚举结果将不再需要单独调用DB.