dotnet / efcore

EF Core is a modern object-database mapper for .NET. It supports LINQ queries, change tracking, updates, and schema migrations.
https://docs.microsoft.com/ef/
MIT License
13.76k stars 3.18k forks source link

AutoInclude not working with unidirectional many-to-many #31380

Open Moerup opened 1 year ago

Moerup commented 1 year ago

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:

public class Book
{
    public int Id { get; set; }

    public string Name { get; set; }
}

Library entity:

public class Library
{
    public int Id { get; set; }

    public string Name { get; set; }

    public List<Book> Books { get; set; } = new();
}

Library configuration:

    public void Configure(EntityTypeBuilder<Library> 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:

        // 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

ajcvickers commented 1 year ago

@Moerup As a workaround, configure many-to-many first. For example:

        builder.HasMany(x => x.Books).WithMany();
        builder.Navigation(x => x.Books).AutoInclude();

Note for triage: this works with one-to-many, presumably because the navigation doesn't later change to a skip navigation.

Moerup commented 1 year ago

Thanks for the workaround, seems to do the trick 👍