• 使用 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" };
  • 相关阅读:
    ADO.net方法
    单例模式(Singleton)的6种实现
    小菜学习设计模式(五)—控制反转(Ioc)
    mysql及linux发行版下载源
    Linux应用总结(1):自动删除n天前日志
    linux挂载mount参数优化
    SQL Server Mysql primary key可更新性分析
    SQL Server 排名函数实现
    MySQL select
    MySQL 数据显示宽度
  • 原文地址:https://www.cnblogs.com/wahaccp/p/3292991.html
Copyright © 2020-2023  润新知