简体   繁体   English

如何使用ADO.net Entity Framework正确加载对象引用

[英]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. Profile.UserID是绑定到User.UserID的FK。 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). 因此,Entity Framework中的Profile.UserID不包含在实体模型中,这就是为什么我的linq查询首先查找User对象然后选择相关的Profile对象(这对我来说感觉很脏)。

Can anyone offer a better solution to: 任何人都可以提供更好的解决方案:

  1. Lookup the Profile object via User.UserID. 通过User.UserID查找Profile对象。
  2. Load the User object reference in the returned Profile object. 在返回的Profile对象中加载User对象引用。

Thanks in advance! 提前致谢!

Try using the Include method 尝试使用Include方法

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. 此方法返回配置文件对象,已加载用户引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM