dotnet / dotnet/efcore

AutoInclude not working with unidirectional many-to-many

Open
#31,380 2 comments 1 reaction 0 assignees View on GitHub
area-model-building customer-reported
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

Using AutoInclude on navigation property when using a unidirectional many to many does not include the related entities.
Explicitly including them in the Linq query works as expected.

A small test repo to reproduce the bug can be found here:
https://github.com/Moerup/ManyToManyAutoInclude

Book entity:
```C#
public class Book
{
public int Id { get; set; }

public string Name { get; set; }
}
```

Library entity:
```C#
public class Library
{
public int Id { get; set; }

public string Name { get; set; }

public List Books { get; set; } = new();
}
```

Library configuration:
```C#
public void Configure(EntityTypeBuilder builder)
{
// This does NOT include books automatically like expected
builder.Navigation(x => x.Books).AutoInclude();

// Unidirectional many to many config => https://learn.microsoft.com/en-us/ef/core/modeling/relationships/many-to-many#unidirectional-many-to-many
builder.HasMany(x => x.Books).WithMany();
}
```

Queries:
```C#
// No related books returned
var libraryWithAutoInclude = dbContext.Libraries.First();

// Related books returned
var libraryWithSpecificInclude = dbContext.Libraries.Include(x => x.Books).First();
```

### Include provider and version information

EF Core version: 7.0.9 and 8.0.0-preview.6.23329.4
Database provider: Microsoft.EntityFrameworkCore.Sqlite and Microsoft.EntityFrameworkCore.SqlServer
Target framework: .NET 7
Operating system: Windows and Linux (tested in docker)
IDE: Visual Studio 2022 17.6.5

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.