I have a database with tables/data, so I have used the db first approach using the following command to scaffold the Models:
dotnet ef dbcontext scaffold "Server=.;Database=MyDb;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -o Models
This has generated the DbContext
and couple of model classes corresponding to my tables. This question involves only 2 models so I am providing the code below:
Person.cs:
using System;
using System.Collections.Generic;
namespace MyApp.Models
{
public partial class Person
{
public Person()
{
Profiles= new HashSet<Profile>();
}
public int Id { get; set; }
public string Email { get; set; } = null!;
public string Password { get; set; } = null!;
public virtual ICollection<Profile> Profiles { get; set; }
}
}
Profile.cs:
using System;
using System.Collections.Generic;
namespace MyApp.Models
{
public partial class Profile
{
public Profile()
{
Sales = new HashSet<Sale>();
}
public int Id { get; set; }
public int PersonId { get; set; }
public string ProfileName { get; set; } = null!;
public virtual Person Person { get; set; } = null!;
public virtual ICollection<Sale> Sales { get; set; }
}
}
In the controller I am trying the following query:
var person = await _context.Person
.AsNoTracking()
.Where(c => c.Email == 'test@testmail.com')
.ToListAsync();
This works. But the following query throws an error:
var profiles = await _context.Person
.AsNoTracking()
.Where(c => c.Email == 'test@testmail.com')
.Include(c => c.Profiles)
.ToListAsync();
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 32. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles.
Path:
$.Profiles.Person.Profiles.Person.Profiles.PersonProfiles.PersonProfiles.PersonProfiles.PersonProfiles.PersonProfiles.PersonProfiles.Person.Id.at System.Text.Json.ThrowHelper.ThrowJsonException_SerializerCycleDetected(Int32 maxDepth)
at System.Text.Json.Serialization.JsonConverter1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state) at System.Text.Json.Serialization.Metadata.JsonPropertyInfo
1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)