Search code examples
c#asp.netentity-frameworkentity-framework-corejson.net

How do I stop Entity Framework Core from creating "Self Referencing Loops" when including navigation properties?


Dear fellow programmers!

My issue is that when I include a navigation property, for example: User.Pets, not only the Pets collection gets included in the entity, but every Pet has a reference trough it's navigation property to the User. (LazyLoading is turned off already)

This would be fine, since we can use the SelfReferencingLoopHandling.Ignore option in the Json serializer, but in not even so large collections, with lots of navigation properties this becomes extremely slow.

The main cause of this is how the serializer handles references. There is also a solution for this as well, it's called "PreserveReferencesHandling.Objects", but it messes up the result JSON file.

So, all summed up, it would be nice to find an option, not to create self referencing loops in the first place, and then trying to solve them.

Thanks everybody!


Solution

  • It is difficult to understand the problem here, I would say that you can use the tag [JsonIgnore] for the properties that you don´t want to return in the result.

    Example:https://www.newtonsoft.com/json/help/html/PropertyJsonIgnore.htm

    Types

    
    public class Account
    {
        public string FullName { get; set; }
        public string EmailAddress { get; set; }
    
        [JsonIgnore]
        public string PasswordHash { get; set; }
    }
    

    Usage:

    Account account = new Account
    {
        FullName = "Joe User",
        EmailAddress = "[email protected]",
        PasswordHash = "VHdlZXQgJ1F1aWNrc2lsdmVyJyB0byBASmFtZXNOSw=="
    };
    
    string json = JsonConvert.SerializeObject(account);
    
    Console.WriteLine(json);
    // {"FullName":"Joe User","EmailAddress":"[email protected]"}