0

I'm trying to deserialize JSON which I'm getting from an external source into an Entity Framework entity class using the following code:

var serializer = new JavaScriptSerializer();
IList<Feature> obj = serializer.Deserialize<IList<Feature>>(json);

The following exception is thrown:

Object of type 'System.Collections.Generic.List1[JustTime.Task]' cannot be converted to type 'System.Data.Objects.DataClasses.EntityCollection1[JustTime.Task]'.

My model is simple: The Feature class has a one-to-many relation to the Tasks class. The problem appears to be the deserializer is trying to create a generic List to hold the collection of tasks instead of an EntityCollection.

I've tried implementing a JavaScriptConverted which would handle System.Collections.Generic.List but it didn't get called by the deserializer.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Barak
  • 135
  • 1
  • 6
  • Which version of .NET are you using? Also, what happens if you remove the assigment to `obj`? – John Saunders Jul 14 '10 at 19:37
  • I'm using .net v4. Removing the assignment doesn't help as the exception occurs inside the deserializer when deserializing a feature's list of tasks. – Barak Jul 15 '10 at 20:28
  • Please check the following links: - http://stackoverflow.com/questions/2002940/json-and-circular-reference-exception - http://stackoverflow.com/questions/5588143/ef-4-1-code-first-json-circular-reference-serialization-error – Korayem Feb 02 '12 at 20:04

1 Answers1

0

You can't assign a list directly to an EF collection. You have to add to it. So deserialize to a POCO and then copy.

Craig Stuntz
  • 125,891
  • 12
  • 252
  • 273
  • This is obviously the easy way out but would require me to duplicate the entire object model just to circumvent a minor technical issue, not really my preferred method of doing things. – Barak Jul 15 '10 at 20:29