EF中Json序列化对象时检测到循环引用的解决办法

时间:2016-07-23 15:12:35   收藏:0   阅读:1800

第一种方法:使用Newtonsoft.Json中的方法注释,在Json序列化的时候忽略导航属性

例:using Newtonsoft.Json;

public class Users

{

  public int Id { get; set; }

  public string LoginId { get; set; }

  public string LoginPwd { get; set; }

  [JsonIgnore]

  public virtual ICollection Roles { get; set; }

}

第二种方法:将要序列化的对象转为匿名对象去掉导航属性

例:var userList = UsersService.GetEntityByPage(pageIndex, pageSize, out recordCount, u =>u.LoginId.Contains(uName), c => c.Id, true);

var data = userList.Select(d => new

        {  d.Id,

          d.LoginId,

          d.LoginPwd

        }).ToList();

return Json(new { rows = data, total = recordCount }, JsonRequestBehavior.AllowGet);

第三种方法:通过设置APP_Start文件夹中的WebApiConfig.cs

例: var json = config.Formatters.JsonFormatter;

      json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!