基本上,我正在尝试使用JavaScriptSerializer将一个简单的实体发送到json。是的,我知道您希望我为此制作一个冗余类,并通过AutoMapper推送它,我要求麻烦。幽默我。
我正在使用Entity Framework 6来获取一个简单的对象来获取一个简单的对象。
这是我的测试代码:
[TestMethod]
public void TestEntityTest()
{
var db = new TestDbContext();
var ent = db.ResupplyForms.SingleOrDefault(e => e.Guid == new Guid("55117161-F3FA-4291-8E9B-A67F3B416097"));
var json = new JavaScriptSerializer().Serialize(ent);
}
非常直接。获取东西并序列化它。
以下内容出错:
An exception of type 'System.InvalidOperationException' occurred in System.Web.Extensions.dll but was not handled in user code
Additional information: A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.ResupplyForm_13763C1B587B4145B35C75CE2D5394EBED19F93943F42503204F91E0B9B4294D'.
这是实体:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
using System.Xml.Serialization;
using System.Data.Entity.Spatial;
using Rome.Model.DataDictionary;
using System.Web.Script.Serialization;
namespace Rome.Model.Form
{
[Table(nameof(ResupplyForm))]
public partial class ResupplyForm
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ResupplyFormID {get;set;}
public Guid Guid {get;set;}
public int? RecordStatus {get;set;}
[ForeignKey(nameof(RecordStatus))]
[ScriptIgnore(ApplyToOverrides = true)]
public virtual LookupItem RecordStatusLookupItem {get;set;}
}
}
我将为LookupItem省略def,因为它进入了我项目的其余部分的模式,并且没有理智的世界,因为我已经将其标记为“被忽略”。
这是一个非常简单的背景:
public class TestDbContext : DbContext
{
public TestDbContext()
: base("data source=.;initial catalog=studybaseline;integrated security=True;pooling=False;multipleactiveresultsets=False")
{
}
public virtual DbSet<ResupplyForm> ResupplyForms { get; set; }
}
现在,政变:使用与我的代码片段完全相同的代码完美运行的LinqPad查询:
var db = new Rome.Model.Form.TestDbContext();
var ent = db.ResupplyForms.SingleOrDefault(e => e.Guid == new Guid("55117161-F3FA-4291-8E9B-A67F3B416097"));
var json = new JavaScriptSerializer().Serialize(ent).Dump();
幸福地回归
{"ResupplyFormID":1,"Guid":"55117161-f3fa-4291-8e9b-a67f3b416097","RecordStatus":null}
我整天都在拔头发,所以任何帮助都会受到赞赏。
答案 0 :(得分:0)
好的,我在一天之后进一步挖掘了这个并找到了原因:它与[ScriptIgnore(ApplyToOverrides = true)]
事物没有没有。它与Entity Framework为每个实体创建的EntityProxy子类有关。我的ResupplyForm实际上并没有在我的测试中用作ResupplyForm ......而是它是一个EntityProxy子类。
此EntityProxy子类添加了一个新成员_entityWrapper。如果EntityProxy正在包装没有导航属性的类,则_entityWrapper不包含任何循环...但是只要添加导航属性,_entityWrapper就会包含循环,这会打破序列化。
模糊的错误消息毁掉了一切。如果JavaScriptSerializer告诉我哪个字段不好,我可以节省很多时间。
无论如何,我应该考虑转换到NewtonSoft,但这会产生自己的问题(对于另一篇文章),但我创建了一个非常原始的解决方法:
public static class JsonSerializerExtensions
{
/// <summary>
/// Convert entity to JSON without blowing up on cyclic reference.
/// </summary>
/// <param name="target">The object to serialize</param>
/// <param name="entityTypes">Any entity-framework-related types that might be involved in this serialization. If null, it will only use the type of "target".</param>
/// <param name="ignoreNulls">Whether nulls should be serialized or not.</param>
/// <returns>Json</returns>
/// <remarks>This requires some explanation: all POCOs used by entites aren't their true form.
/// They're subclassed proxies of the object you *think* you're defining. These add a new member
/// _EntityWrapper, which contains cyclic references that break the javascript serializer.
/// This is Json Serializer function that skips _EntityWrapper for any type in the entityTypes list.
/// If you've a complicated result object that *contains* entities, forward-declare them with entityTypes.
/// If you're just serializing one object, you can omit entityTypes.
///</remarks>
public static string ToJsonString(this object target, IEnumerable<Type> entityTypes = null, bool ignoreNulls = true)
{
var javaScriptSerializer = new JavaScriptSerializer();
if(entityTypes == null)
{
entityTypes = new[] { target.GetType() };
}
javaScriptSerializer.RegisterConverters(new[] { new EntityProxyConverter(entityTypes, ignoreNulls) });
return javaScriptSerializer.Serialize(target);
}
}
public class EntityProxyConverter : JavaScriptConverter
{
IEnumerable<Type> _EntityTypes = null;
bool _IgnoreNulls;
public EntityProxyConverter(IEnumerable<Type> entityTypes, bool ignoreNulls = true) : base()
{
_EntityTypes = entityTypes;
_IgnoreNulls = ignoreNulls;
}
public override IEnumerable<Type> SupportedTypes
{
get
{
return _EntityTypes;
}
}
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)
{
var result = new Dictionary<string, object>();
if (obj == null)
{
return result;
}
var properties = obj.GetType().GetProperties(
System.Reflection.BindingFlags.Public
| System.Reflection.BindingFlags.Instance
| System.Reflection.BindingFlags.GetProperty
);
foreach (var propertyInfo in properties.Where(p => Attribute.GetCustomAttributes(p, typeof(ScriptIgnoreAttribute), true).Length == 0))
{
if (!propertyInfo.Name.StartsWith("_"))
{
var value = propertyInfo.GetValue(obj, null);
if (value != null || !_IgnoreNulls)
{
result.Add(propertyInfo.Name, propertyInfo.GetValue(obj, null));
}
}
}
return result;
}
}
你必须传入这些类(让我们记住,它是动态生成的代理类)才能使用它,遗憾的是,它可能会因任何合理的对象图而悲惨地失败,但它会起作用简单的单个对象和数组等。它也无法与JsonResult一起使用,因为这些覆盖不能在那里使用。