1
I’m running a very simple test, where I have two entities with a 1-1 relationship between them:
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Job Job { get; set; }
}
public class Job
{
public int Id { get; set; }
public string Title { get; set; }
public User User { get; set; }
public int UserId { get; set; }
}
Mapping between the two:
public class UserMapping : IEntityTypeConfiguration<User>
{
public void Configure(EntityTypeBuilder<User> builder)
{
builder.HasKey(u => u.Id);
builder.HasOne(u => u.Job).WithOne(j => j.User);
}
}
public class JobMapping : IEntityTypeConfiguration<Job>
{
public void Configure(EntityTypeBuilder<Job> builder)
{
builder.HasKey(j => j.Id);
builder.Property(j => j.Title).IsRequired();
}
}
By returning to the user list without including their Jobs, I succeed.
However, when performing a Include, the Jobs list is returned, but causes a circular reference:
var users = _context.Users.Include(u => u.Job).ToList();
For the circular reference not to occur, is it necessary that I remove Userid from the Job entity? Because it doesn’t make sense to me that to return all users with their Jobs I first need to consult the Jobs and include the Users. I would like to be able to consult users and Jobs, and if necessary, perform a include on any of them.
If I add Newtonsoftjson support in Startup, there is a configuration for it to ignore circular references when serializing content for JSON. It is recommended to leave the query the way it is and simply use this Newtonsoft option to get around the problem?
public virtual User User { get; set; }
– Leandro Angelo
Setting the property to virtual does not change the result of the query. In addition I am performing a include manually.
– Carltee
This behavior must be related to what we call Lazy Loading no Entity Framework. If applicable, understand the pros and cons of disabling it.
Configuration.LazyLoadingEnabled = false;
Entity Framework - Lazy Loading– Leandro Amarilha