HUGE performance hit with one-to-one foreign key in Entity Framework?

I am going to make this REALLY simple. I have two tables.

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; }
}

Basically they are two tables that share a primary key in a 1-1 relationship. Whether these should be combined into one or not, I don't know, I am basing this off of an existing database.

Now, the issue I have is when I access it.

THIS CODE GOES FAST(second, maybe two):

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;
}

THIS CODE GOES REALLY SLOW(10-30 seconds):

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;
}

Why does my code take so much longer when I access the UserProfile from the user table?!

Answers


Probably because you are lazy loading UserProfile here. This means that for each iteration in your loop you make an individual call to the DB to load UserProfile when you attempt to access the email address.

I'm not sure how you are creating the userList collection, but assuming you are doing a simple query over your User table you can use Include to eager load any properties that you would like to have up front:

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

Now the performance hit is limited to when this query is intially executed, enumerating over the results would no longer require individual calls to the DB.


Need Your Help

How to replace all parts of a string by regex that stats with a \ and ends with \ or space or {?

javascript regex string replace space

I want to create an RTF reader, and I want to get the plain text part. But I can't "delete" the commands from the incoming string 's'...

“save link as” bulk download

hyperlink save bulk

I have a list of links in an html file and I want to perform a "save link as" for all of them so it downloads all the files into one folder.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.