简体   繁体   中英

Detach EF object from databasecontext to avoid circular reference

Based on Wes Grants answer in this thread: Serializing Entity Framework problems

I tried the following code:

string sid = HttpContext.Current.Request["Sid"];
SYSTEM system = context.SYSTEM.Where(s => s.SYSTEM_ID.Contains(sid)).First();

context.Detach(system);

HttpContext.Current.Response.Write(serializer.Serialize(system));

But I still get the circular reference exception. Did I miss something obvious here? Thanks

If you're using EntityObjects and not POCOs you cannot do this. The reason is that if your SYSTEM type derives from EntityObject it inherits some properties that will also be serialized. See here and here .

The solution is either

  • to switch to using POCOs instead of EntityObjects
  • to write your own converter, as explained in the SO question you linked
  • to project your queries into anonymous types and serialize those using the JavaScriptSerializer
  • to map your entities to data transfer objects (DTOs; in principal they're data contracts) and transmit those

EDIT:

If you ARE already using POCO the cause could be that EF internally creates proxy classes for your POCOs in order for change tracking and lazy loading to work. These proxy classes are dynamically created and can cause serialization to fail.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM