【发布时间】:2015-11-04 12:50:56
【问题描述】:
我正在尝试将(实体框架 6)实体序列化为 json。在通过 AsNoTracking() 方法进行序列化之前,我确保该条目在内存中,但是我收到一个错误,因为它无法从条目中引用的不同表中接收值。
Inner Exception: When an object is returned with a NoTracking merge option, Load can only be called when the EntityCollection or EntityReference does not contain objects.
Exception: JsonSerializationException: Error getting value from 'TABLE_X' on 'System.Data.Entity.DynamicProxies....
代码:
List<Location> locations = new DbContext().Locations.Where(x => x.Type == 1).Take(5).AsNoTracking().ToList();
string s = JsonConvert.SerializeObject(locations, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
我想要做的就是返回一个序列化实体的字符串。我不担心其他对象,只担心位置实体。
当我尝试处理连接然后进行 json 序列化时,我收到了错误:The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
我只想序列化我的列表,我不想返回/序列化任何外部依赖项。
【问题讨论】:
-
为什么需要序列化该实体?
-
因为我想将它存储在一个 json 文件中以备后用。例如。使用有效/有价值的数据进行单元测试。
-
我会理解存储 POCO 类,但现在存储 EF 实体,但你可能有不同的要求。
-
如果您将导航属性指定为
Virtual,您应该能够直接从数据库中序列化整个实体。无需关闭代理或创建其他模型。或者,您可以预先加载所有导航属性?
标签: c# entity-framework entity-framework-6 jsonserializer