相关疑难解决方法(0)

Json和循环引用异常

我有一个对象,它具有对另一个对象的循环引用.鉴于这些对象之间的关系,这是正确的设计.

为了显示

Machine => Customer => Machine
Run Code Online (Sandbox Code Playgroud)

正如我所料,当我尝试使用Json来序列化机器或客户对象时,我遇到了一个问题.我不确定的是如何解决这个问题,因为我不想打破Machine和Customer对象之间的关系.解决此问题的选项有哪些?

编辑

目前我正在使用Controller基类提供的Json方法.所以我正在做的序列化基本如下:

Json(machineForm);
Run Code Online (Sandbox Code Playgroud)

asp.net-mvc serialization json circular-reference

39
推荐指数
3
解决办法
4万
查看次数

从数据库加载没有代理类?

在实体框架4中是否可以选择在没有使用代理类的情况下将某些查询加载到POCO中?(出于缓存该对象的目的,以备将来只读使用).我正在使用存储库 - 服务模式.

我的意思是:

var order = _orderService.GetById(1);
// after order is loaded then we can see in the debugger that:
// order.Customer is of type System.Data.Entity.DynamicProxy.Customer_17631AJG_etc
Run Code Online (Sandbox Code Playgroud)

我想要的是order.Customer实际使用POCO类型MyApp.Models.Entities.Customer而不是该类型的代理.

编辑:根据Ladislav建议在存储库中添加"GetUnproxied"方法,我做了这个改动:

// this is the current method that must return a DynamicProxy
public IQueryable<T> GetQuery()
{
    return ObjectSet.AsQueryable();
}

// this is the new additional method that must return the plain POCO
public IQueryable<T> GetReadOnly()
{
    ObjectContext.ContextOptions.ProxyCreationEnabled = false;
    var readOnly = ObjectSet.AsQueryable();
    ObjectContext.ContextOptions.ProxyCreationEnabled = true;
    return readOnly; …
Run Code Online (Sandbox Code Playgroud)

c# entity-framework proxy-classes poco

7
推荐指数
1
解决办法
9216
查看次数

在将Entity Framework对象图序列化为Json时防止StackOverflowException

我想将一个实体框架自我跟踪实体完整对象图(一对多关系中的父/子)序列化为Json.

为了序列化我使用ServiceStack.JsonSerializer.

这就是我的数据库的样子(为简单起见,我删除了所有不相关的字段):

ERD

我以这种方式获取完整的个人资料图:

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

4
推荐指数
2
解决办法
1万
查看次数