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" };
  • 相关阅读:
    JS中的prototype
    Php5.3的lambda函数以及closure(闭包)
    JavaScript事件委托的技术原理
    css 里层元素撑不开外层元素
    扩展VirtualBox虚拟机磁盘容量
    easyUI 条件查询 跟分页数据展示写在了一起的
    (转)Hibernate中关于多表连接查询hql 和 sql 返回值集合中对象问题
    有想去北京工作的的想法了
    第一次写oracle SQL 两个表链接查询
    第三天 SQL小记
  • 原文地址:https://www.cnblogs.com/wahaccp/p/3292991.html
Copyright © 2011-2022 走看看