keysersoze
keysersoze

Reputation: 777

Circular reference with EF4

I am trying to return an Entity Framework 4 object with children to an jQuery JSON AJAX function but I get a circular reference error - in short my method looks like this

[WebMethod]
public static JSONObject Get()
{
  WebHelper.JSONObject lJSONObject = new WebHelper.JSONObject();

  lJSONObject.Object =  Repository.Parent.Include("Child.Child").FirstOrDefault();

  return lJSONObject;
}

if I do not include children the functions works fine, but with children the circular reference occurs. Any ideas what I can do to fix this?

Upvotes: 2

Views: 1751

Answers (3)

Oleg Rudckivsky
Oleg Rudckivsky

Reputation: 930

Try adding ScriptIgnore attribute to property Parent. See for more details: http://msdn.microsoft.com/en-us/library/system.web.script.serialization.scriptignoreattribute.aspx

-- EDIT --

They will be overwritten if you do this in designer file. But you can try adding metadata type:

[MetadataType(typeof(TestMD))]
public partial class Test
{
}

public class TestMD
{
    [ScriptIgnore]
    public object Parent { get; set; }
}

Upvotes: 1

Daniel T.
Daniel T.

Reputation: 38400

Do you have to return a JSONObject? If not, you can try using Json.NET, which will handle circular references properly:

var settings = new JsonSerializerSettings
                   {
                       ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                   };

JsonConvert.SerializeObject(object, Formatting.Indented, settings);

My guess is that the JsonObject is simply a wrapper that will serialize the entity and put it on the response stream, which is simple enough to do manually.

Upvotes: 5

eestein
eestein

Reputation: 5114

I had the same problem. Not sure if there's any other solution, but I got it to work creating my own Serialize method.

Upvotes: 0

Related Questions