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!

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Backwards from what I wanted returned, but using the Include method and a similar syntax I was able to resolve my issue. Thanks bendewey!
Yes, that's exactly what I changed it too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.