我会让这个变得非常简单。 我有两张 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/