我有一个实体框架实体,我想序列化为一个json对象.我环顾四周,发现json.net(http://james.newtonking.com/projects/json-net.aspx)应该能够使用"开箱即用"的循环引用来序列化对象.所以我尝试使用
string json = JsonConvert.SerializeObject(/* my ef entity */);
Run Code Online (Sandbox Code Playgroud)
但我仍然得到同样的错误.问题可能是我需要使用ReferenceLoopHandling.Ignore和a ContractResolver,但我不知道如何使用它们.任何帮助深表感谢!谢谢
像其他几个人一样,我在序列化Entity Framework对象时遇到问题,因此我可以通过AJAX以JSON格式发送数据.
我有以下服务器端方法,我试图通过jQuery使用AJAX调用
[WebMethod]
public static IEnumerable<Message> GetAllMessages(int officerId)
{
SIBSv2Entities db = new SIBSv2Entities();
return (from m in db.MessageRecipients
where m.OfficerId == officerId
select m.Message).AsEnumerable<Message>();
}
Run Code Online (Sandbox Code Playgroud)
通过AJAX调用此结果会导致此错误:
A circular reference was detected while serializing an object of type \u0027System.Data.Metadata.Edm.AssociationType
Run Code Online (Sandbox Code Playgroud)
这是因为实体框架创建循环引用以保持所有对象相关且可访问服务器端的方式.
我从(http://hellowebapps.com/2010-09-26/producing-json-from-entity-framework-4-0-generated-classes/)中找到了以下代码,声称通过封顶解决了这个问题参考的最大深度.我已经添加了下面的代码,因为我必须稍微调整它以使其工作(网站上的代码中缺少所有有角度的括号)
using System.Web.Script.Serialization;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System;
public class EFObjectConverter : JavaScriptConverter
{
private int _currentDepth = 1;
private readonly int _maxDepth = 2;
private readonly List<int> _processedObjects = new List<int>();
private …Run Code Online (Sandbox Code Playgroud) 我想将一个实体框架自我跟踪实体完整对象图(一对多关系中的父/子)序列化为Json.
为了序列化我使用ServiceStack.JsonSerializer.
这就是我的数据库的样子(为简单起见,我删除了所有不相关的字段):

我以这种方式获取完整的个人资料图:
public Profile GetUserProfile(Guid userID)
{
using (var db = new AcmeEntities())
{
return db.Profiles.Include("ProfileImages").Single(p => p.UserId == userId);
}
}
Run Code Online (Sandbox Code Playgroud)
问题是尝试序列化它:
Profile profile = GetUserProfile(userId);
ServiceStack.JsonSerializer.SerializeToString(profile);
Run Code Online (Sandbox Code Playgroud)
生产一个StackOverflowException.我相信这是因为EF提供了一个无限模型,可以将串行器拧紧.也就是说,我可以称之为:profile.ProfileImages[0].Profile.ProfileImages[0].Profile ...等等.
如何"展平"我的EF对象图或以其他方式阻止ServiceStack.JsonSerializer进入堆栈溢出情况?
jsonserializer entity-framework-4 self-tracking-entities c#-4.0 servicestack
我在寻找将实体及其子实体转换为 DTO 对象的好方法时遇到问题。在这篇文章中,我创建了伪代码,这是一个简化的示例,省略了数据库上下文、DTO 对象。假设我有一个父实体和子实体:
public class Parent {
int Id;
string Name;
List<Child> Children;
}
public class Child {
int Id;
string Name;
Parent Parent;
int ParentId;
}
Run Code Online (Sandbox Code Playgroud)
我研究了两种可能性,但未能找到好的解决方案。请看一下这两个例子以及我陷入困境的地方。
1. 使用选择查询的示例
为了将所有父实体检索为 DTO,我可以在控制器中执行以下操作:
public IHttpActionResult GetParents()
{
var children = from c in _context.Children
select new ChildDTO()
{
Id = c.Id,
Name= c.Name
};
var parents = from p in _context.Parents
select new ParentDTO()
{
Id = p.Id,
Name = p.Name
Children = children.ToList(),
};
return parents;
}
Run Code Online (Sandbox Code Playgroud)
这将返回父 DTO …