zoukankan      html  css  js  c++  java
  • 使用 Entity Framework 返回 JsonResult 时循环引

    使用 Entity Framework 返回 JsonResult 时循环引用的避免。

    发表时间: 2011-03-23 06:29:17 | 评论: 3 | 查看: 340 | 来自: LUKIYA_NEVERLAND
     

    最近在做公司的一个Dealer WHOLE SALE系统,使用了Entity Framework MVC3,在返回JsonResult时遇到了循环引用的问题。

    刚开始使用 [ScriptIgnore] 来避免此问题,可是发现Designer.cs改动时会把这个属性给自动删除,继续查阅了很多资料,自定义了一个JavaScriptConverter解决了问题,下面是代码。

      public class EFJavaScriptConverter : JavaScriptConverter
      {
        public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
          throw new NotImplementedException();
        }
    
        public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
        {
          IDictionary<string, object> result = new Dictionary<string, object>();
          //
          Type type = obj.GetType();
          PropertyInfo[] properties = type.GetProperties();
          foreach (PropertyInfo property in properties)
          {
            bool allowSerialize = IsAllowSerialize(property);
            if (allowSerialize)
            {
              result[property.Name] = property.GetValue(obj, null);
            }
          }
          //
          return result;
        }
    
        private bool IsAllowSerialize(PropertyInfo property)
        {
          object[] attrs = property.GetCustomAttributes(true);
          foreach (object attr in attrs)
          {
            if (attr is System.Data.Objects.DataClasses.EdmScalarPropertyAttribute)
            {
              return true;
            }
          }
          //
          return false;
        }
    
        public override IEnumerable<Type> SupportedTypes
        {
          get
          {
            yield return typeof(System.Data.Objects.DataClasses.EntityObject);
          }
        }
      }

    使用方法:

    IList<OLX_Users> list = _MembershipService.GetUsers();
    
    System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
    js.RegisterConverters(new List<EFJavaScriptConverter>() { new EFJavaScriptConverter() });
    
    string content = js.Serialize(list);
    
    return new ContentResult { Content = content, ContentType = "application/json" };
  • 相关阅读:
    利用virtual box安装ubuntu16.4,没有继续(下一步)的解决方案
    最好用的几个谷歌镜像(推荐理由:无广告)
    vs2017和vs2019专业版和企业版
    c# List根据某个属性进行分类,变成以属性名称作为分类的多个List
    vs2015安装编辑神器:resharper10.0
    c# 正则表达式替换字符串中常见的特殊字符
    IL中间语言指令大全
    c#进阶一:使用ILDASM来查看c#中间语言
    SQL server脚本语句积累
    SQLServer事务在C#当中的应用
  • 原文地址:https://www.cnblogs.com/wahaccp/p/3292991.html
Copyright © 2011-2022 走看看