MVC4+EntityFramework时候遇到的问题

来源:互联网 发布:网络硬盘录像机主板 编辑:程序博客网 时间:2024/04/29 21:43

1.返回JSON数据的问题:

当使用Ajax请求Controller里面返回数据的时候,会要求返回一个Json数据,然后使用EntityFramework生成的数据实体modle直接返回是不行的,因为EF中的实体除了本身的属性以外,还存在有导航属性(Navigation Property)这样在Json序列化的时候会报错,大致意思就是:出现了循环引用,解决方法如下:
            AreaService areaService = new AreaService();            //List<HN_CITY> city = areaService.GetCity(id).ToList();            var cityList = areaService.GetCity(id).Select(c => new {id=c.ID,name=c.CITY});            if (null!=cityList)            {                return Json(cityList,JsonRequestBehavior.AllowGet);            }            else            {                return null;            }
也就是我们new一个匿名对象取代EF的model对象(HN_CITY),这样在序列化的时候就不会报错了。
0 0
原创粉丝点击