JSON.NET Error Self referencing loop detected for type
Asked Answered
A

27

623

I tried to serialize POCO class that was automatically generated from Entity Data Model .edmx and when I used

JsonConvert.SerializeObject 

I got the following error:

Error Self referencing loop detected for type System.data.entity occurs.

How do I solve this problem?

Armbruster answered 13/9, 2011 at 5:25 Comment(4)
possible duplicate of Serialize one to many relationships in Json.netTinatinamou
when you are using Linq and MVC : stackoverflow.com/a/38241856Paella
when using .NET Core 2: https://mcmap.net/q/64045/-json-net-error-self-referencing-loop-detected-for-typeOlin
This error happened to me, when I wanted to serialize the result of an async method call (a Task) and forgot to prefix the await statement.Neusatz
J
561

Use JsonSerializerSettings

  • ReferenceLoopHandling.Error (default) will error if a reference loop is encountered. This is why you get an exception.
  • ReferenceLoopHandling.Serialize is useful if objects are nested but not indefinitely.
  • ReferenceLoopHandling.Ignore will not serialize an object if it is a child object of itself.

Example:

JsonConvert.SerializeObject(YourPOCOHere, Formatting.Indented, 
new JsonSerializerSettings 
{ 
        ReferenceLoopHandling = ReferenceLoopHandling.Serialize
});

Should you have to serialize an object that is nested indefinitely you can use PreserveObjectReferences to avoid a StackOverflowException.

Example:

JsonConvert.SerializeObject(YourPOCOHere, Formatting.Indented, 
new JsonSerializerSettings 
{ 
        PreserveReferencesHandling = PreserveReferencesHandling.Objects
});

Pick what makes sense for the object you are serializing.

Reference http://james.newtonking.com/json/help/

Jaeger answered 3/1, 2012 at 11:37 Comment(6)
I encountered the error when serializing a datatable. I used ReferenceLoopHandling = ReferenceLoopHandling.Ignore for it to workDivinize
If there are reference loops in the data, using ReferenceLoopHandling.Serialize will cause the serializer to go into an infinite recursive loop and overflow the stack.Deenadeenya
Correct. As the question is about an EF model also a valid concern. Amended to give all available options.Jaeger
I've encountered this same error when trying to serialize an object... however, the object doesn't have any references other than an enum type..Junno
for me EF is the main cause for this problem because self referenced entities are all over the place.Anchylose
For the problem in the question i.e. 'Self referencing loop detected with type', 3rd option works to fix it i.e. ReferenceLoopHandling.IgnoreTodtoday
T
84

The fix is to ignore loop references and not to serialize them. This behaviour is specified in JsonSerializerSettings.

Single JsonConvert with an overload:

JsonConvert.SerializeObject(YourObject, Formatting.Indented,
    new JsonSerializerSettings() {
        ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
    }
);

Global Setting with code in Application_Start() in Global.asax.cs:

JsonConvert.DefaultSettings = () => new JsonSerializerSettings {
     Formatting = Newtonsoft.Json.Formatting.Indented,
     ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};

Reference: https://github.com/JamesNK/Newtonsoft.Json/issues/78

Thurlow answered 16/9, 2013 at 16:8 Comment(3)
Why do you set the format to indented when you do the global setting?Esra
Absolutely what we needed to solve this problem (discovered during a deployment)! You da man....thanks for saving us time!!Kershaw
I solved my issus by adding "JsonConvert.DefaultSettings" = () => new JsonSerializerSettings {....} in the class "Startup.cs"Demo
S
52

The simplest way to do this is to install Json.NET from nuget and add the [JsonIgnore] attribute to the virtual property in the class, for example:

    public string Name { get; set; }
    public string Description { get; set; }
    public Nullable<int> Project_ID { get; set; }

    [JsonIgnore]
    public virtual Project Project { get; set; }

Although these days, I create a model with only the properties I want passed through so it's lighter, doesn't include unwanted collections, and I don't lose my changes when I rebuild the generated files...

Subcortex answered 8/10, 2014 at 11:0 Comment(1)
Best answer using Newton JSONCrape
O
21

In .NET Core 1.0, you can set this as a global setting in your Startup.cs file:

using System.Buffers;
using Microsoft.AspNetCore.Mvc.Formatters;
using Newtonsoft.Json;

// beginning of Startup class

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc(options =>
        {
            options.OutputFormatters.Clear();
            options.OutputFormatters.Add(new JsonOutputFormatter(new JsonSerializerSettings(){
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            }, ArrayPool<char>.Shared));
        });
    }
Oliva answered 14/7, 2016 at 18:49 Comment(1)
But in this case, if I want to be aware that this property is Ignored I will not get any exception then.Bors
O
19

If you're using .NET Core 2.x, update your ConfigureServices section in Startup.cs

https://learn.microsoft.com/en-us/ef/core/querying/related-data/serialization

    public void ConfigureServices(IServiceCollection services)
    {
    ...

    services.AddMvc()
        .AddJsonOptions(options => 
          options.SerializerSettings.ReferenceLoopHandling = 
            Newtonsoft.Json.ReferenceLoopHandling.Ignore
        );

    ...
    }

If you're using .NET Core 3.x - 5.0, without MVC, it would be:

# startup.cs
services.AddControllers()
  .AddNewtonsoftJson(options =>
      options.SerializerSettings.ReferenceLoopHandling =
        Newtonsoft.Json.ReferenceLoopHandling.Ignore
   );

For .NET 6.0, the only difference is it now goes in Program.cs.

# program.cs
services.AddControllers()
   .AddNewtonsoftJson(options =>
      options.SerializerSettings.ReferenceLoopHandling = 
        Newtonsoft.Json.ReferenceLoopHandling.Ignore);

This reference loop handling is almost mandatory if you're using Entity Framework and database-first design pattern.

Olin answered 9/2, 2018 at 15:31 Comment(7)
what if i dont use services.AddMvc()?Mercurial
is this a bad practice?Mohl
At first glance you might think this is a bad practice as it might override "intentional design" of avoiding the old "infinite loop" problem. However, if you think about your use cases for classes, you may need them to refer to each other. For example, you may want to access both Trees>Fruits and also Fruits>Trees.Olin
Also, if you're using a database-first design pattern with something like Entity Framework, depending on how you setup your foreign keys in your database, it will automatically create these cyclical references, so you pretty much have to use this setting if you're reverse engineering your classes.Olin
Dear Dave Skender, how to fix with .NET Core 6.0? Thank youLevirate
@HOÀNGLONG, it's the exact same snippet as what's shown for .NET 5.0; however, the big difference between the two frameworks is that this goes into the Program.cs file, starting in .NET 6.0.Olin
Also, I do not know if there's a Json.NET equivalent, so I'm still using Newtonsoft.Json. If anyone's tried configuring successfully with Json.NET, please share.Olin
U
10

We can add these two lines into DbContext class constructor to disable Self referencing loop, like

public TestContext()
        : base("name=TestContext")
{
    this.Configuration.LazyLoadingEnabled = false;
    this.Configuration.ProxyCreationEnabled = false;
}
Unhappy answered 25/11, 2015 at 14:49 Comment(4)
This is one of the simplest one and working like a charm. Voted up, thanks a lot...Sacring
Like I wrote in the other question: I dont like this kind of answers because you are turning off a feature of EF6 that is enabled by default and this piece of code might break other parts of the program. You should explain what this does and what kind of repercussions it has.Archimandrite
@ElMac you are right, but if we don't need that feature so why can't use this solution?Unhappy
@SanjayNishad I don't mind if you don't need the feature. It's just about the users that don't know what they are disabling.Archimandrite
E
10

To serialize usin NEWTONSOFTJSON when you have loop issue, in my case I did not need modify global.asax or either apiconfig. I just use JsonSerializesSettings ignoring Looping handling.

JsonSerializerSettings jss = new JsonSerializerSettings();
jss.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
var lst = db.shCards.Where(m => m.CardID == id).ToList();
string json = JsonConvert.SerializeObject(lst, jss);
Elsewhere answered 21/9, 2017 at 13:28 Comment(1)
If anyone else came here for a one liner to go in the watch window so it's text searchable: Newtonsoft.Json.JsonConvert.SerializeObject(objToSerialize, new Newtonsoft.Json.JsonSerializerSettings() {ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore});Onaonager
I
8

You can apply an attribute to the property too. The [JsonProperty( ReferenceLoopHandling = ... )] attribute is well suited to this.

For example:

/// <summary>
/// Represents the exception information of an event
/// </summary>
public class ExceptionInfo
{
    // ...code omitted for brevity...

    /// <summary>
    /// An inner (nested) error.
    /// </summary>
    [JsonProperty( ReferenceLoopHandling = ReferenceLoopHandling.Ignore, IsReference = true )]
    public ExceptionInfo Inner { get; set; }

    // ...code omitted for brevity...    
}

Hope that helps, Jaans

Influx answered 10/6, 2014 at 13:11 Comment(1)
That's the one I needed. My root object inherited from a certain model but it also had a property with that same model. When both had the same ids value I had this self reference loop issue. Adding the ignore on the propery fixed this. Thanks!Millihenry
S
4

To ignore loop references and not to serialize them globally in MVC 6 use the following in startup.cs:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().Configure<MvcOptions>(options =>
        {
            options.OutputFormatters.RemoveTypesOf<JsonOutputFormatter>();
            var jsonOutputFormatter = new JsonOutputFormatter();
            jsonOutputFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            options.OutputFormatters.Insert(0, jsonOutputFormatter);
        });
    }
Seisin answered 16/5, 2015 at 13:53 Comment(0)
D
4

Just update services.AddControllers() in Startup.cs file

services.AddControllers()
  .AddNewtonsoftJson(options =>
      options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
   );
Darkle answered 18/8, 2020 at 15:14 Comment(0)
G
3

C# code:

var jsonSerializerSettings = new JsonSerializerSettings
{
    ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
    PreserveReferencesHandling = PreserveReferencesHandling.Objects,
};

var jsonString = JsonConvert.SerializeObject(object2Serialize, jsonSerializerSettings);

var filePath = @"E:\json.json";

File.WriteAllText(filePath, jsonString);
Gaza answered 1/6, 2020 at 6:8 Comment(2)
This is essentially the same guidance as offered in @DalSoft‘s highly-rated answer from eight years ago, but with far less explanation.Preamble
Hope It will solve issue but please add explanation of your code with it so user will get perfect understanding which he/she really wants.Pennipennie
P
2

Use this in WebApiConfig.cs class :

var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
Pawsner answered 2/7, 2015 at 7:28 Comment(0)
B
2

For me I had to go a different route. Instead of trying to fix the JSON.Net serializer I had to go after the Lazy Loading on my datacontext.

I just added this to my base repository:

context.Configuration.ProxyCreationEnabled = false;

The "context" object is a constructor parameter I use in my base repository because I use dependency injection. You could change the ProxyCreationEnabled property anywhere you instantiate your datacontext instead.

http://techie-tid-bits.blogspot.com/2015/09/jsonnet-serializer-and-error-self.html

Blais answered 18/9, 2015 at 18:29 Comment(0)
B
2

I had this exception and my working solution is Easy and Simple,

Ignore the Referenced property by adding the JsonIgnore attribute to it:

[JsonIgnore]
public MyClass currentClass { get; set; }

Reset the property when you Deserialize it:

Source = JsonConvert.DeserializeObject<MyObject>(JsonTxt);
foreach (var item in Source)
        {
            Source.MyClass = item;
        }

using Newtonsoft.Json;

Bors answered 9/11, 2017 at 17:54 Comment(1)
This is the Magic I need. Solve It [JsonIgnore]Deni
C
2

People have already talked about [JsonIgnore] being added to the virtual property in the class, for example:

[JsonIgnore]
public virtual Project Project { get; set; }

I will also share another option, [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] which omits the property from serialization only if it is null:

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public virtual Project Project { get; set; }
Chamaeleon answered 12/7, 2018 at 19:55 Comment(0)
R
2

Team:

This works with ASP.NET Core; The challenge to the above is how you 'set the setting to ignore'. Depending on how you setup your application it can be quite challenging. Here is what worked for me.

This can be placed in your public void ConfigureServices(IServiceCollection services) section.

services.AddMvc().AddJsonOptions(opt => 
        { 
      opt.SerializerSettings.ReferenceLoopHandling =
      Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        });
Revolute answered 29/10, 2018 at 20:0 Comment(0)
L
2

In .Net 5.x, update your ConfigureServices method in startup.cs with the below code

public void ConfigureServices(IServiceCollection services)
{
    ----------------
    ----------------
    services.AddMvc().AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve;
    });
    ------------------
}

By default, serialization (System.Text.Json.Serialization) does not support objects with cycles and does not preserve duplicate references. Use Preserve to enable unique object reference preservation on serialization and metadata consumption to read preserved references on deserialization. MSDN Link

Lamination answered 31/1, 2021 at 19:47 Comment(0)
S
1

My Problem Solved With Custom Config JsonSerializerSettings:

services.AddMvc(
  // ...
               ).AddJsonOptions(opt =>
                 {
                opt.SerializerSettings.ReferenceLoopHandling =
                    Newtonsoft.Json.ReferenceLoopHandling.Serialize;
                opt.SerializerSettings.PreserveReferencesHandling =
                    Newtonsoft.Json.PreserveReferencesHandling.Objects;
                 });
Stolen answered 28/5, 2019 at 8:41 Comment(0)
Q
1

For .NET Core 3.0, update the Startup.cs class as shown below.

public void ConfigureServices(IServiceCollection services)
{
...

services.AddControllers()
    .AddNewtonsoftJson(
        options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
    );

...
}

See: https://devblogs.microsoft.com/aspnet/asp-net-core-updates-in-net-core-3-0-preview-5/

Questionless answered 25/10, 2019 at 15:56 Comment(1)
Tried this but does not work for me @ .NET Core 5Instruction
C
1

Please also make sure to use await and async in you method. You can get this error if your object are not serialized properly.

Cortex answered 2/12, 2019 at 2:4 Comment(1)
Same happened to meBrick
O
1

I've inherited a database application that serves up the data model to the web page. Serialization by default will attempt to traverse the entire model tree and most of the answers here are a good start on how to prevent that.

One option that has not been explored is using interfaces to help. I'll steal from an earlier example:

public partial class CompanyUser
{
    public int Id { get; set; }
    public int CompanyId { get; set; }
    public int UserId { get; set; }

    public virtual Company Company { get; set; }

    public virtual User User { get; set; }
}

public interface IgnoreUser
{
    [JsonIgnore]
    User User { get; set; }
}

public interface IgnoreCompany
{
    [JsonIgnore]
    User User { get; set; }
}

public partial class CompanyUser : IgnoreUser, IgnoreCompany
{
}

No Json settings get harmed in the above solution. Setting the LazyLoadingEnabled and or the ProxyCreationEnabled to false impacts all your back end coding and prevents some of the true benefits of an ORM tool. Depending on your application the LazyLoading/ProxyCreation settings can prevent the navigation properties loading without manually loading them.

Here is a much, much better solution to prevent navigation properties from serializing and it uses standard json functionality: How can I do JSON serializer ignore navigation properties?

Ocotillo answered 9/7, 2020 at 1:23 Comment(0)
P
0

Simply place Configuration.ProxyCreationEnabled = false; inside the context file; this will solve the problem.

public demEntities()
    : base("name=demEntities")
{
    Configuration.ProxyCreationEnabled = false;
}
Postmark answered 5/10, 2016 at 15:7 Comment(0)
B
0

I was facing the same problem and I tried using JsonSetting to ignore the self-referencing error its kinda work until I got a class which self-referencing very deeply and my dot-net process hangs on Json writing value.

My Problem

    public partial class Company : BaseModel
{
    public Company()
    {
        CompanyUsers = new HashSet<CompanyUser>();
    }

    public string Name { get; set; }

    public virtual ICollection<CompanyUser> CompanyUsers { get; set; }
}

public partial class CompanyUser
{
    public int Id { get; set; }
    public int CompanyId { get; set; }
    public int UserId { get; set; }

    public virtual Company Company { get; set; }

    public virtual User User { get; set; }
}

public partial class User : BaseModel
{
    public User()
    {
        CompanyUsers = new HashSet<CompanyUser>();
    }

    public string DisplayName { get; set; }
    public virtual ICollection<CompanyUser> CompanyUsers { get; set; }

}

You can see the problem in User class it's referencing to CompanyUser class which is a self-referencing.

Now, I'm calling the GetAll Method which includes all the relational properties.

cs.GetAll("CompanyUsers", "CompanyUsers.User");

On this stage my DotNetCore process hangs on Executing JsonResult, writing value ... and never come. In my Startup.cs, I've already set the JsonOption. For some reason EFCore is including nested property which I'm not asking Ef to give.

    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

expected behavior should be this

Hey EfCore can you please include "CompanyUsers" data as well in my Company class so that i can easily access the data.

then

Hey EfCore can you also please include the "CompanyUsers.User" data as well so that i can easily access the data like this Company.CompanyUsers.First().User.DisplayName

at this stage i should only get this "Company.CompanyUsers.First().User.DisplayName" and it should not give me Company.CompanyUsers.First().User.CompanyUsers which causing the self-referencing issue; Technically it shouldn't give me User.CompanyUsers as CompanyUsers is a navigational property. But, EfCore get very excited and giving me User.CompanyUsers.

So, I decided to write an extension method for property to be excluded from the object (it's actually not excluding it's just setting the property to null). Not only that it will also work on array properties as well. below is the code I'm also going to export the nuget package for other users (not sure if this even helps someone). Reason is simple because I'm too lazy to write .Select(n => new { n.p1, n.p2}); I just don't want to write select statement to exclude only 1 property!

This is not the best code (I'll update at some stage) as I have written in a hurry and though this might help someone who wants to exclude (set null) in the object with arrays also.

    public static class PropertyExtensions
{
    public static void Exclude<T>(this T obj, Expression<Func<T, object>> expression)
    {
        var visitor = new PropertyVisitor<T>();
        visitor.Visit(expression.Body);
        visitor.Path.Reverse();
        List<MemberInfo> paths = visitor.Path;
        Action<List<MemberInfo>, object> act = null;

        int recursiveLevel = 0;
        act = (List<MemberInfo> vPath, object vObj) =>
        {

            // set last propert to null thats what we want to avoid the self-referencing error.
            if (recursiveLevel == vPath.Count - 1)
            {
                if (vObj == null) throw new ArgumentNullException("Object cannot be null");

                vObj.GetType().GetMethod($"set_{vPath.ElementAt(recursiveLevel).Name}").Invoke(vObj, new object[] { null });
                return;
            }

            var pi = vObj.GetType().GetProperty(vPath.ElementAt(recursiveLevel).Name);
            if (pi == null) return;
            var pv = pi.GetValue(vObj, null);
            if (pi.PropertyType.IsArray || pi.PropertyType.Name.Contains("HashSet`1") || pi.PropertyType.Name.Contains("ICollection`1"))
            {
                var ele = (IEnumerator)pv.GetType().GetMethod("GetEnumerator").Invoke(pv, null);

                while (ele.MoveNext())
                {
                    recursiveLevel++;
                    var arrItem = ele.Current;

                    act(vPath, arrItem);

                    recursiveLevel--;
                }

                if (recursiveLevel != 0) recursiveLevel--;
                return;
            }
            else
            {
                recursiveLevel++;
                act(vPath, pv);
            }

            if (recursiveLevel != 0) recursiveLevel--;

        };

        // check if the root level propert is array
        if (obj.GetType().IsArray)
        {
            var ele = (IEnumerator)obj.GetType().GetMethod("GetEnumerator").Invoke(obj, null);
            while (ele.MoveNext())
            {
                recursiveLevel = 0;
                var arrItem = ele.Current;

                act(paths, arrItem);
            }
        }
        else
        {
            recursiveLevel = 0;
            act(paths, obj);
        }

    }

    public static T Explode<T>(this T[] obj)
    {
        return obj.FirstOrDefault();
    }

    public static T Explode<T>(this ICollection<T> obj)
    {
        return obj.FirstOrDefault();
    }
}

above extension class will give you the ability to set the property to null to avoid the self-referencing loop even arrays.

Expression Builder

    internal class PropertyVisitor<T> : ExpressionVisitor
{
    public readonly List<MemberInfo> Path = new List<MemberInfo>();

    public Expression Modify(Expression expression)
    {
        return Visit(expression);
    }


    protected override Expression VisitMember(MemberExpression node)
    {
        if (!(node.Member is PropertyInfo))
        {
            throw new ArgumentException("The path can only contain properties", nameof(node));
        }

        Path.Add(node.Member);
        return  base.VisitMember(node);
    }
}

Usages:

Model Classes

    public class Person
{
    public string Name { get; set; }
    public Address AddressDetail { get; set; }
}

public class Address
{
    public string Street { get; set; }
    public Country CountryDetail { get; set; }
    public Country[] CountryDetail2 { get; set; }
}

public class Country
{
    public string CountryName { get; set; }
    public Person[] CountryDetail { get; set; }
}

Dummy Data

           var p = new Person
        {
            Name = "Adeel Rizvi",
            AddressDetail = new Address
            {
                Street = "Sydney",
                CountryDetail = new Country
                {
                    CountryName = "AU"
                }
            }
        };

        var p1 = new Person
        {
            Name = "Adeel Rizvi",
            AddressDetail = new Address
            {
                Street = "Sydney",
                CountryDetail2 = new Country[]
                {
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A1" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A2" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A3" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A4" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A5" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A6" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A7" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A8" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A9" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A1" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A2" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A3" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A4" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A5" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A6" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A7" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A8" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A9" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },

                }
            }
        };

Cases:

Case 1: Exclude only property without any array

p.Exclude(n => n.AddressDetail.CountryDetail.CountryName);

Case 2: Exclude property with 1 array

p1.Exclude(n => n.AddressDetail.CountryDetail2.Explode().CountryName);

Case 3: Exclude property with 2 nested array

p1.Exclude(n => n.AddressDetail.CountryDetail2.Explode().CountryDetail.Explode().Name);

Case 4: EF GetAll Query With Includes

var query = cs.GetAll("CompanyUsers", "CompanyUsers.User").ToArray();
query.Exclude(n => n.Explode().CompanyUsers.Explode().User.CompanyUsers);
return query;

You have notice that Explode() method its also a extension method just for our expression builder to get the property from array property. Whenever there is a array property use the .Explode().YourPropertyToExclude or .Explode().Property1.MyArrayProperty.Explode().MyStupidProperty. Above code helps me to avoid the self-referencing so deep as deep i want. Now i can use GetAll and exclude the property which i don;t want!

Thank you for reading this big post!

Biegel answered 22/2, 2020 at 11:9 Comment(0)
A
0

Very similar to others on here, Solved by using the Serializer settings. However mine originated since I was using the FromObject side of things as I needed a JObject to work with.

This means just need to create the default serializer and apply settings to that. Simple fix becomes this

 var deserializerSettings = new JsonSerializerSettings()
        {
            ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
            PreserveReferencesHandling = PreserveReferencesHandling.Objects,
        };

        var serializer = JsonSerializer.CreateDefault(deserializerSettings);
            
        JObject jsonObject = (JObject)JToken.FromObject(mySelfRefernceObject, serializer);
Ambie answered 13/1, 2023 at 11:28 Comment(0)
H
0

Had this issue coming from one of third party nuget package. Didn't have the option to change configurations or serialization. Installing Newtonsoft.Json package in my consumer project sorted the issue.

<PackageReference Include="Newtonsoft.Json" Version="13.0.2" />
Hwu answered 27/2, 2023 at 0:45 Comment(0)
L
-1

For not looping this worked for me-
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,

I've solved it all here - Entity Framework children serialization with .Net Core 2 WebAPI https://gist.github.com/Kaidanov/f9ad0d79238494432f32b8407942c606

Will appreciate any remarks. maybe someone can use it sometime.

Lateen answered 17/6, 2018 at 9:52 Comment(0)
R
-2

I liked the solution that does it from Application_Start() as in the answer here

Apparently I could not access the json objects in JavaScript using the configuration within my function as in DalSoft's answer as the object returned had "\n \r" all over the (key, val) of the object.

Anyway whatever works is great (because different approaches work in different scenario based on the comments and questions asked) though a standard way of doing it would be preferable with some good documentation supporting the approach.

Rehabilitation answered 22/4, 2017 at 14:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.