8 c# entity-framework jsonserializer entity-framework-6
我正在尝试将(Entity Framework 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....
Run Code Online (Sandbox Code Playgroud)
码:
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 });
Run Code Online (Sandbox Code Playgroud)
我想要做的就是返回一个序列化实体的字符串.我不担心其他对象,仅仅是位置实体.
当我尝试处理连接然后json序列化我收到错误: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
我只想序列化我的列表,我不想返回/序列化任何外来依赖项.
这是一个EF动态代理问题,您必须禁用它以使代码正常工作
在您继承的类中 DbContext
public class MyModelEntities : DbContext
{
public MyModelEntities()
{
//just disable it like this
Configuration.ProxyCreationEnabled = false;
}
}
Run Code Online (Sandbox Code Playgroud)
主要是发生的事情是你JsonConvert正在尝试序列化这样的对象System.Data.Entity.DynamicProxies.Location_5E43C6C196972BF0754973E48C9C941092D86818CD94005E9A759B70BF6E48E6
由于代理无法找到,因为它是动态创建的
| 归档时间: |
|
| 查看次数: |
4086 次 |
| 最近记录: |