【问题标题】:How do I properly load Object References with ADO.net Entity Framework如何使用 ADO.net Entity Framework 正确加载对象引用
【发布时间】:2009-03-27 17:15:23
【问题描述】:

我正在做的工作,但这是错误的,我知道。

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

谁能提供更好的解决方案:

  1. 通过 User.UserID 查找 Profile 对象。
  2. 在返回的 Profile 对象中加载 User 对象引用。

提前致谢!

【问题讨论】:

    标签: c# linq entity-framework


    【解决方案1】:

    尝试使用Include 方法

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

    此方法返回配置文件对象,其中已加载用户引用。

    【讨论】:

    • 从我想要返回的内容向后退,但使用 Include 方法和类似的语法我能够解决我的问题。谢谢本德威!
    • 是的,我也是这么改的。
    猜你喜欢
    • 2010-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-14
    • 1970-01-01
    • 2017-11-30
    • 2011-07-26
    • 1970-01-01
    相关资源
    最近更新 更多