I have a Blazor WebApp in which I load data with EF Core. Now I get the following error when displaying the data on a page because of reference loops, the data is loaded in an Syncfusion ComboBox:
<SfComboBox TValue="Contact" TItem="Contact" @bind-Value="item.Owner" DataSource="Contacts" Placeholder="Besitzer">
<ComboBoxFieldSettings Value="@nameof(Contact.FullName)"></ComboBoxFieldSettings>
</SfComboBox>
The traceback:
Error: System.Text.Json.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. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles. Path: $.Items.Owner.Items.Owner.Items.Owner.Items.Owner.Items.Owner.Items
...
...
JsonSerializerOptions options, WriteStack& state)
at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
at System.Text.Json.Serialization.JsonConverter`1.WriteCore(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
at System.Text.Json.Serialization.Metadata.JsonTypeInfo`1.Serialize(Utf8JsonWriter writer, T& rootValue, Object rootValueBoxed)
at System.Text.Json.JsonSerializer.WriteString[TValue](TValue& value, JsonTypeInfo`1 jsonTypeInfo)
at System.Text.Json.JsonSerializer.Serialize[TValue](TValue value, JsonSerializerOptions options)
at Syncfusion.Blazor.DropDowns.SfDropDownList`2.GetDataByValue(TValue ddlValue)
at Syncfusion.Blazor.DropDowns.SfDropDownList`2.InitValueAsync()
at Syncfusion.Blazor.DropDowns.SfDropDownList`2.OnAfterRenderAsync(Boolean firstRender)
at Syncfusion.Blazor.DropDowns.SfComboBox`2.OnAfterRenderAsync(Boolean firstRender)
at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)
I have tried to set to Json Reference Handler but it does not work:
builder.Services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>(options => options.SerializerOptions.ReferenceHandler = ReferenceHandler.Preserve);
builder.Services.ConfigureHttpJsonOptions(jsonOptions =>
{
jsonOptions.SerializerOptions.ReferenceHandler = ReferenceHandler.Preserve;
});
Classes used:
public class Item
{
public Contact Owner { get; set; }
}
public class Contact
{
public List<Item> Items { get; set; } = new List<Item>();
}