序列化实体框架问题

序列化实体框架问题,第1张

序列化实体框架问题

我通过以下课程解决了这些问题:

public class EFJavascriptSerializer : JavascriptSerializer  {    public EFJavascriptSerializer()    {      RegisterConverters(new List<JavascriptConverter>{new EFJavascriptConverter()});    }  }

public class EFJavascriptConverter : JavascriptConverter  {    private int _currentDepth = 1;    private readonly int _maxDepth = 1;    private readonly List<object> _processedObjects = new List<object>();    private readonly Type[] _builtInTypes = new[]    {      typeof(int?),      typeof(double?),      typeof(bool?),      typeof(bool),      typeof(byte),      typeof(sbyte),      typeof(char),      typeof(decimal),      typeof(double),      typeof(float),      typeof(int),      typeof(uint),      typeof(long),      typeof(ulong),      typeof(short),      typeof(ushort),      typeof(string),      typeof(DateTime),      typeof(DateTime?),      typeof(Guid)  };    public EFJavascriptConverter() : this(1, null) { }    public EFJavascriptConverter(int maxDepth = 1, EFJavascriptConverter parent = null)    {      _maxDepth = maxDepth;      if (parent != null)      {        _currentDepth += parent._currentDepth;      }    }    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavascriptSerializer serializer)    {      return null;    }    public override IDictionary<string, object> Serialize(object obj, JavascriptSerializer serializer)    {      _processedObjects.Add(obj.GetHashCode());      var type = obj.GetType();      var properties = from p in type.GetProperties() where p.CanRead && p.GetIndexParameters().Count() == 0 &&       _builtInTypes.Contains(p.PropertyType) select p;      var result = properties.ToDictionary(         p => p.Name,         p => (Object)TryGetStringValue(p, obj));      if (_maxDepth >= _currentDepth)      {        var complexProperties = from p in type.GetProperties()          where p.CanRead &&     p.GetIndexParameters().Count() == 0 &&     !_builtInTypes.Contains(p.PropertyType) &&     p.Name != "RelationshipManager" &&     !AllreadyAdded(p, obj)          select p;        foreach (var property in complexProperties)        {          var complexValue = TryGetValue(property, obj);          if(complexValue != null)          { var js = new EFJavascriptConverter(_maxDepth - _currentDepth, this); result.Add(property.Name, js.Serialize(complexValue, new EFJavascriptSerializer()));          }        }      }      return result;    }    private bool AllreadyAdded(PropertyInfo p, object obj)    {      var val = TryGetValue(p, obj);      return _processedObjects.Contains(val == null ? 0 : val.GetHashCode());    }    private static object TryGetValue(PropertyInfo p, object obj)    {      var parameters = p.GetIndexParameters();      if (parameters.Length == 0)      {        return p.GetValue(obj, null);      }      else      {        //cant serialize these        return null;      }    }    private static object TryGetStringValue(PropertyInfo p, object obj)    {      if (p.GetIndexParameters().Length == 0)      {        var val = p.GetValue(obj, null);        return val;      }      else      {        return string.Empty;      }    }    public override IEnumerable<Type> SupportedTypes    {      get      {        var types = new List<Type>();        //ef types        types.AddRange(Assembly.GetAssembly(typeof(DbContext)).GetTypes());        //model types        types.AddRange(Assembly.GetAssembly(typeof(baseViewModel)).GetTypes());        return types;      }    }  }

您现在可以安全地拨打

new EFJavascriptSerializer().Serialize(obj)

更新 :从Telerik v1.3
+版本开始,您现在可以覆盖GridActionAttribute.CreateActionResult方法,因此可以通过应用自定义

[GridAction]
属性轻松地将此Serializer集成到特定的控制器方法中:

[Grid]public ActionResult _GetOrders(int id){    return new GridModel(Service.GetOrders(id));}

public class GridAttribute : GridActionAttribute, IActionFilter  {        /// <summary>    /// Determines the depth that the serializer will traverse    /// </summary>    public int SerializationDepth { get; set; }    /// <summary>    /// Initializes a new instance of the <see cref="GridActionAttribute"/> class.    /// </summary>    public GridAttribute()      : base()    {      ActionParameterName = "command";      SerializationDepth = 1;    }    protected override ActionResult CreateActionResult(object model)    {          return new EFJsonResult      {       Data = model,       JsonRequestBehavior = JsonRequestBehavior.AllowGet,       MaxSerializationDepth = SerializationDepth      };    }}

最后..

public class EFJsonResult : JsonResult  {    const string JsonRequest_GetNotAllowed = "This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.";    public EFJsonResult()    {      MaxJsonLength = 1024000000;      RecursionLimit = 10;      MaxSerializationDepth = 1;    }    public int MaxJsonLength { get; set; }    public int RecursionLimit { get; set; }    public int MaxSerializationDepth { get; set; }    public override void ExecuteResult(ControllerContext context)    {      if (context == null)      {        throw new ArgumentNullException("context");      }      if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&          String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))      {        throw new InvalidOperationException(JsonRequest_GetNotAllowed);      }      var response = context.HttpContext.Response;      if (!String.IsNullOrEmpty(ContentType))      {        response.ContentType = ContentType;      }      else      {        response.ContentType = "application/json";      }      if (ContentEncoding != null)      {        response.ContentEncoding = ContentEncoding;      }      if (Data != null)      {        var serializer = new JavascriptSerializer        {          MaxJsonLength = MaxJsonLength,          RecursionLimit = RecursionLimit        };        serializer.RegisterConverters(new List<JavascriptConverter> { new EFJsonConverter(MaxSerializationDepth) });        response.Write(serializer.Serialize(Data));      }    }


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5623030.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存