© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
46 replies
eysidi

❔ Serializing related object EF

Hello all,

I have 2 models

public class City {
    [Key]
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    [Required]
    public string CountryName { get; set; }
    public Coordinates? Coordinates { get; set; }
}

public class Coordinates {
    public int Id { get; set; }
    public double X { get; set; }
    public double Y { get; set; }
    public int CityId { get; set; }
    public City City { get; set; } = null!;
}
public class City {
    [Key]
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    [Required]
    public string CountryName { get; set; }
    public Coordinates? Coordinates { get; set; }
}

public class Coordinates {
    public int Id { get; set; }
    public double X { get; set; }
    public double Y { get; set; }
    public int CityId { get; set; }
    public City City { get; set; } = null!;
}


And I would like to include
Coordinates
Coordinates
of
City
City
in my response however I get error
JsonException: A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 64
JsonException: A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 64


My query is

return db.Cities
        .Where(c => c.Name.ToLower().Contains(city.ToLower()))
        .Include(c => c.Coordinates)
        .ToList();
return db.Cities
        .Where(c => c.Name.ToLower().Contains(city.ToLower()))
        .Include(c => c.Coordinates)
        .ToList();


I have googled it and found different approaches but from the examples I saw, this should be working.

Why does this happen?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

✅ EF CORE, get request wont return related object
C#CC# / help
2y ago
Updating Immutable object with ef
C#CC# / help
2y ago
✅ Serializing a dictonary without path in root object
C#CC# / help
3y ago
Serilog loses List-object- property values when serializing
C#CC# / help
4y ago