开发者

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 f开发者_StackOverflowix this?


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.


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; }
}


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜