[英]How to serialize into a json from entity?
我正在嘗試將(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....
碼:
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.
我只想序列化我的列表,我不想返回/序列化任何外來依賴項。
這是EF
的動態代理問題,您必須禁用它以使代碼正常工作
在您的類中繼承自DbContext
public class MyModelEntities : DbContext
{
public MyModelEntities()
{
//just disable it like this
Configuration.ProxyCreationEnabled = false;
}
}
主要是發生的事情是你的JsonConvert
正在嘗試序列化像這樣的對象System.Data.Entity.DynamicProxies.Location_5E43C6C196972BF0754973E48C9C941092D86818CD94005E9A759B70BF6E48E6
由於代理無法找到,因為它是動態創建的
您無需調用AsNoTracking
方法即可將所需實體加載到內存中。 ToList
方法將完成這項工作。
現在關於您的問題,是因為JSON序列化程序正在嘗試訪問Location
實例上的每個屬性,並且您最終可能因為啟用了延遲加載而查詢整個數據庫。 所以,你有兩個選擇:
JsonIgnore
屬性。 就個人而言,我更喜歡第一個,當我需要加載一個具有某個特定相關實體的實體時,我使用預先加載來加載它作為查詢的一部分:
context.Locations
.Include(l=>l.State)//eager loading an hypothetical related entity
.Where(x => x.Type == 1)
.Take(5)
.ToList();
如果您的對象圖不是太復雜,那么不同的方法可能是創建簡單的POCO類,其中您的Location
將從中映射。 讓我們說LocationModel
。 這可以手動映射,例如使用AutoMapper映射。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.