Kappers
Kappers

Reputation: 1331

How do I properly load Object References with ADO.net Entity Framework

What I'm doing works, but it's just wrong, I know it.

    public Profile GetProfile(int id)
    {
        Profile profile = (
            from u in en.User where u.UserID == id 
                select u.Profile.FirstOrDefault()
            ).First();

        if (profile.UserReference.Value == null)
            profile.UserReference.Load();

        return profile;
    }

Profile.UserID is a FK tied to User.UserID. Thus, Profile.UserID is not included in the Entity Model by the Entity Framework, which is why my linq query looks up the User object first and then selects the related Profile object (which feels very dirty to me).

Can anyone offer a better solution to:

  1. Lookup the Profile object via User.UserID.
  2. Load the User object reference in the returned Profile object.

Thanks in advance!

Upvotes: 1

Views: 2584

Answers (1)

bendewey
bendewey

Reputation: 40235

Try using the Include method

public Profile GetProfile(int id)
{
  return (from p in db.Profiles.Include("User")
          where p.User.UserId == id
          select p).FirstOrDefault();
}

This method returns the profile object, with the User reference loaded already.

Upvotes: 4

Related Questions