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

标签 c# linq entity-framework

我所做的工作有效,但这是错误的,我知道。

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

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

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

提前致谢!

最佳答案

尝试使用 Include方法

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

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

关于c# - 如何使用 ADO.net Entity Framework 正确加载对象引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/690666/

相关文章:

c# - 如何获取所有子文件夹及其文件 - UWP

visual-studio - 如何创建 Entity Framework 项目?

c# - 如何编写 linq 语句来获取一组记录中的最后一条记录

c# - 关于 .Net ftp 类和被动模式 c# 的使用

c# - 使用数据库而不是内存存储身份服务器 4

c# - 在 powershell 和 C# 之间共享变量

c# - 无法将手动匿名项目添加到 IQueryable

linq - Go 泛型是否允许 LINQ to Objects 等效?

c# - 创建依赖于多个搜索字段的动态 LINQ 查询的最有效方法?

c# - 将自定义实体映射到数据库列