Entity Framework causes circular references?
I have a problem with EF Code First and it complains about a circular reference in the generated proxies. Maybe we have a convention conflict that causes EF to create a circular reference on the fly? The dataset produces no errors when simply passed directly to the JSON serializer.
/* Assume all dependencies and namespaces are referenced and used */
///the base object
public class A {
[Key]
public int AId { set; get; }
//the tree
public B MyB { set; get; }
}
//the tree nodes
public class B {
[Key]
public int BId { set; get; }
public int AId { set; get; }
public int ParendId { set; get; }
public virtual ICollection<B> Children { set; get; }
}
///the context
public class ABContext : DbContext {
public DbSet<A> As { set; get; }
public DbSet<B> Bs { set; get; }
}
///later in a controller...
[HttpGet]
public JsonResult Get(string sid)
{
int id = int.Parse(sid);
using (ABContext abc = new ABContext()) {
A a = abc.As.Where(i=>开发者_如何学Ci.AId==id).Single();
return Json(a, JsonRequestBehavior.AllowGet);
}
}
Thoughts and comments are all very welcome!
Thank you, Alexander Brevig
I had the same problem.
http://garfbradazweb.wordpress.com/2011/09/22/mvc-3-entity-framework-and-serializing-jsoncircular-references/
A bit of googling, and it seems the JavaScriptSerializer has gets it knickers in a twist trying to traverse your Entity Framework objects which have relationships.
精彩评论