I had this problem and solved it by adding the Newtonsoft.Json.JsonIgnoreAttribute to the property causing the loop. Obviously, that property won't be serialized. To help with this problem, I typically will have both the foreign reference ID and the foreign class in my entities. I realize this is not intuitive (or super great OO), but it is the way recommended by Julia Lerman in her book Programming Entity Framework: Code First. I've found it helps smooth out several problems with Entity Framework.
public class SomeEntity
{
[JsonIgnore]
public ForeignEntity SomeForeignEntity {get;set;}
public Guid ForeignEntityId {get;set;}
}
Update: I forgot to mention I also needed to disable proxies on the DbContext like so:
dataContext.Configuration.ProxyCreationEnabled = false;
If you are writing the code for a service (which seems likely if you are serializing), then this is probably not a problem, but there are some things you lose when the proxy creation is disabled. See here: http://www.sellsbrothers.com/posts/Details/12665 for more details.
I am using the MS Web Api, so I just disable the the proxy creation when I construct my controller:
public class MailingApiController : ApiController
{
public MailingApiController()
{
PreventDeepSerialization();
}
private static void PreventDeepSerialization()
{
var dataContext = Injector.Get<IIntertwyneDbContext>();
dataContext.Configuration.ProxyCreationEnabled = false;
}
....