【发布时间】:2012-02-27 09:15:00
【问题描述】:
我想将Entity Framework Self-Tracking Entities 完整对象图(一对多关系中的父+子)序列化为Json。
对于序列化,我使用 ServiceStack.JsonSerializer。
这就是我的数据库的样子(为简单起见,我删除了所有不相关的字段):
我以这种方式获取完整的个人资料图:
public Profile GetUserProfile(Guid userID)
{
using (var db = new AcmeEntities())
{
return db.Profiles.Include("ProfileImages").Single(p => p.UserId == userId);
}
}
问题在于尝试序列化它:
Profile profile = GetUserProfile(userId);
ServiceStack.JsonSerializer.SerializeToString(profile);
产生一个StackOverflowException。
我相信这是因为 EF 提供了一个无限模型,将序列化器搞砸了。也就是说,我可以在技术上调用:profile.ProfileImages[0].Profile.ProfileImages[0].Profile ... 等等。
如何“展平”我的 EF 对象图或以其他方式防止 ServiceStack.JsonSerializer 遇到堆栈溢出情况?
注意: 我不想将我的对象投影到匿名类型(如 these suggestions),因为这会引入非常长且难以维护的代码片段)。
【问题讨论】:
标签: c#-4.0 entity-framework-4 self-tracking-entities servicestack jsonserializer