dotnet / dotnet/efcore

In a one-to-many query, if AutoInclude is configured, when querying 'many', there will be an extra 'many' in 'one' of 'many'

Open
#34,502 3 comments 0 reactions 0 assignees View on GitHub
area-query customer-reported
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

I know this is hard to understand. Let me give you an example. There are two entities, factories and areas. One factory corresponds to multiple areas, and one area has one factory. There is a set of data, one factory and one area. When I query the area, I expect it should be a area, a factory under the area, and a area under the factory. But in fact, it is a area, a factory under the area, and two area under the factory, and these two area are the same.

Factory

public class Factory : CommonEntity, IEntityTypeBuilder
{
public string? Description { get; set; }
public UniversalType Type { get; set; }
public List Areas { get; set; }
public new void Configure(EntityTypeBuilder entityBuilder, DbContext dbContext, System.Type dbContextLocator)
{
base.Configure(entityBuilder, dbContext, dbContextLocator);
//entityBuilder.HasMany(x => x.Areas).WithOne(x => x.Factory);
entityBuilder.Navigation(x => x.Areas).AutoInclude();
//entityBuilder.HasOne(x => x.Type);
entityBuilder.Navigation(x => x.Type).AutoInclude();
}
}

area

public class Area : CommonEntity, IEntityTypeBuilder
{
public string? Description { get; set; }
public Factory? Factory { get; set; }
public UniversalType Type { get; set; }
public new void Configure(EntityTypeBuilder entityBuilder, DbContext dbContext, Type dbContextLocator)
{
base.Configure(entityBuilder, dbContext, dbContextLocator);
entityBuilder.Navigation(x => x.Factory).AutoInclude();
entityBuilder.Navigation(x => x.Type).AutoInclude();
}
}

query

private TEntity GetOneObject(int Id, string Name)
where TEntity : CommonEntity, new()
{
using (var repository = Db.GetRepository())
{
return repository.Context.Set().AsNoTracking().FirstOrDefault(x => x.Id == Id || x.Name == Name);
}
}

result
![image](https://github.com/user-attachments/assets/fcfe2041-a67a-4b92-a328-db9112d44ddd)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.