views:

1171

answers:

1

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!

+4  A: 

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.

bendewey
Backwards from what I wanted returned, but using the Include method and a similar syntax I was able to resolve my issue. Thanks bendewey!
Kappers
Does this query work better for you scenario?
bendewey
Yes, that's exactly what I changed it too.
Kappers