I’m using a library (Telerik) for ASP.NET MVC 3.
I’ve a problem with all functionnalities which needs to return by AJAX some data:
I’m using EF4 to connect my database, and I’ve(and need) navigation properties in both ways(Imagine, a User which have some Posts and one Post have an User).
The problem is that the library is using the JavaScriptSerializer, which encodes data with JSON.
The error that I get
A circular reference was detected while serializing an object of type ‘System.Data.Entity.DynamicProxies.Employee_34048F4F6A98297F826C798A27640C7383E95E8EA8282EC8A5F738FA0C77CBC3’.”
Exception, which is right, because the parent has reference to its children, and children have reference to its parent.
I’ve already found some workaround, but nothing which fully satisfy me:
- Use data server binding: cannot, the functionnality has to work in ajax(Its a pager for grid, which loads the next elements when the page has been scrolled to the end)
- Use an anonymous objects: not flexible, because if I’ve a field in addition in the database, I must add it in all my anonymous object, and in addition, if I need to have a sub-collection which I want, it’s boring to also create objects for all element of this sublist.
- Use ViewModel: Almost same problem, if I’ve one more field, I must add this fields on all viewModel, and I’ve to create an view model for all my 60 views, with exact same fields than my model, …
- Use the NonSerializedAttribute : I don’t know how to put in my T4 template which generate my POCO objects, and I’m not sure it will works: sometime the main object is the children, sometimes it’s the parent, the empty relations has to be another one.
I had almost the same problem with WCF, and I created a serialized which knows handling circular reference, can we do the same here? Or is there a way to manage this?
If not, I suppose that the best way is to use “ViewModel”, but is there a way to accelerate those creation? Like a generic object, which takes in the constructor the EF object and remove circular reference? anything else?
Thank you very much
Actually, rather than
[NonSerialized], it is[ScriptIgnore]that you would need. I would approach this from one of 2 angles, though:use
RegisterConvertersand write a custom converter that specifies all the properties except the parent one (this could probably be automated too, maybe using a bespoke class-level attribute like[SkipSerialize("Parent")]added in apartial class– that is probably over-complicating things, though).simply: don’t serialize the EF POCO, but instead use a DTO – it sounds like this is what you mean in your
ViewModelanswer. Personally, I have no issue with having an “entity” (EF/POCO) version of a class and a very similar but different DTO version – their intent is different, and in my mind it doesn’t violate DRY.