0

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

Community
  • 1
  • 1
Johan
  • 35,120
  • 54
  • 178
  • 293
  • Use view models. Don't try to JSON serialize some EF autogenerated models. – Darin Dimitrov Nov 03 '11 at 22:29
  • @DarinDimitrov View models in web forms? :) – Johan Nov 03 '11 at 22:32
  • of course. View models should be used in any properly designed GUI oriented application. For example in your case view models will help you solve your circular dependency issue. Object graphs with circular dependencies cannot be JSON serialized as the JSON specification doesn't provide anything for them. – Darin Dimitrov Nov 03 '11 at 22:42
  • It is not correct to suggest using ViewModels. Typically a ViewModel includes much more than what the service can provide, foremost a ViewModel often has behavior defined. You can however only send data over the net, so you're never sending a ViewModel to a client, you're always sending a DTO or DataContract that the client generates a ViewModel out of. – Andreas Nov 04 '11 at 08:04

1 Answers1

0

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.

Community
  • 1
  • 1
Andreas
  • 6,447
  • 2
  • 34
  • 46
  • Thanks for answering. I have a poco version of my system. Wouldnt that already be used when im creating a new instance of SYSTEM? – Johan Nov 04 '11 at 13:26
  • @Johan okay, maybe the problem is that EF creates a proxy object in the background. I updated the answer. – Andreas Nov 04 '11 at 18:19