I have a circular object reference which stops an object from being serialized into json. I was trying to use ScriptIgnoreAttribute on the property that is causing problems, but it didn't seem to work. I believe that's because I'm using EF convention with virtual keyword:
[ScriptIgnore]
public virtual SomeObject SomeObject { get; set; }
The other side of this relationship looks like this
public virtual ICollection<OtherObject> OtherObjects { get; set; }
I have no additional mappings.
How can I resolve this?
The problem is that each of the OtherObject
objects has a back reference to SomeObject
, which in turn has a collection of OtherObject
, etc.
I would recommend creating a viewmodel class which contains only the properties you need. Then, map your entity to the viewmodel class. Return the viewmodel class instance instead of the raw entity.
The other alternative is to tell the json serializer to stop serializing circular references. I prefer the first approach though.
You can also influence EF behavior (ex. disable lazy loading by removing the virtual
keyword) or by changing the query.
But really, I prefer the viewmodel approach. I find that using viewmodels solves not only this but other problems as well.