RHarris
RHarris

Reputation: 11177

Why am I getting circular reference error with Json serializer with a unidirectional object?

I have the following model:

public class Address
{
   public int Id {get; set;}
   public string Street1 {get; set;}
   ...
   public int CountryId {get; set;}
   public Country Country {get; set;}
}

public class Country
{
    public int Id {get; set;}
    public string Name {get; set;}
    public string ISOCode {get; set;}
    public string Continent {get; set;}
    public string ISOCode {get; set;}
    public string Languages {get; set;}
}

public class Church
{
    public int Id {get; set;}
    public string Name {get; set;}
    public int CountryId {get; set;}
    public Country Country {get; set;}
    public int AddressId {get; set;}
    public virtual Address Address {get; set;}
    public string Phone {get; set;}
}

Does the serializer think that I have some kind of bi-directional relation going on with Country since both Church and Address have a Country object? If not, then why do I get circular reference when trying to serialize a church object?

EDIT: What's even more confusing to me is that I'm not even including Country (on church) when I query:

var results = _context.Churches.Include(c => c.Address).Include(c => c.Address.Country).AsQueryable();

Entity Framework Context is configured so that LasyLoading is not enabled. Seems to me that Church.Country should be null and shouldn't even be an issue here.

Upvotes: 0

Views: 165

Answers (1)

Jakub Konecki
Jakub Konecki

Reputation: 46008

I believe the problem lies with the fact that you're serializing EF entities, which are in fact proxies with references to DataContext. Inspect them in the debugger.

You will have to use JsonObject(MemberSerialization.OptIn) attribute and mark your properties with JsonProperty attribute. More info in documentation.

Upvotes: 1

Related Questions