代码之家  ›  专栏  ›  技术社区  ›  4imble

实体框架(4.0)如何排除相关表

  •  1
  • 4imble  · 技术社区  · 16 年前

    我刚刚更新到使用ef 4.0,在我使用linq 2 sql之前。

    我有个问题:

        var UserList = this.repository.GetUsers();
        return Json(UserList, JsonRequestBehavior.AllowGet);
    

    这会产生错误:“ A circular reference was detected while serializing an object of type

    这促使该代码在L2S中运行良好:

      var UserList = this.repository.GetUsers();
          foreach (User u in UserList){
              u.Subscriptions = null;
          }
      return Json(UserList, JsonRequestBehavior.AllowGet);
    

    我如何才能阻止ef查看subscriptions表,我只想要userlist,没有相关的属性,上面的示例似乎不适用于此。

    干杯, 科汉

    2 回复  |  直到 10 年前
        1
  •  2
  •   Ian Mercer    16 年前

    在将用户列表传递给json序列化程序之前对其进行投影,这样它就不会深入到任何ef生成的属性中。

    var UserList = this.repository.GetUsers().Select(user => new {Name = user.Name, Email = user.Email, ...);
    
        2
  •  1
  •   Hooman    10 年前

    有更简单的方法。
    你要做的就是 懒散的 上下文配置上的属性

    它将很像下面的一行:

    context.Configuration.LazyLoadingEnabled = false;
    

    然后您可以按如下方式进行查询:

    var userList = from u in context.users
                   select u;
    

    希望有帮助