Why EF Core automatically load related entities when property referring to the entity is accessed in Select method of Linq?

When I accessing to referring property in Select extension method of Linq, EF Core (5.21) automatically load (Join in SQL) this entity.

This test passes correctly, i.e. it means that EF automatically loads the property, regardless of the value of context.ChangeTracker.LazyLoadingEnabled.

I tried to make the referring properties not virtual, it didn't help either.

Is it possible disable autoload of referring properties in such cases?

    [Theory]
    [InlineData(false)]
    [InlineData(true)]
    public void IncludingAfterSelect(bool lazyLoadingEnabled)
    {
        using (var context = new MyContext(_options))
        {
            context.ChangeTracker.LazyLoadingEnabled = lazyLoadingEnabled;

            var models = context.AddrGroupsObjects.Take(1);

            var modelsList = models.ToList();
            Assert.Single(modelsList);
            Assert.Null(modelsList[0].AgoAobj);

            var dtos = models.Select(x => new AddrGroupsObjectDto()
            {
                Id = x.AgoId,
                AddrObjectId = x.AgoAobjId,
                AddrObject = x.AgoAobj == null ? null : new AddrObjectDto() { AobjId = x.AgoAobj.AobjId }
            });

            var dtosList = dtos.ToList();

            Assert.Single(dtosList);
            Assert.NotNull(dtosList[0].AddrObject);

            modelsList = models.ToList();
            Assert.Single(modelsList);
            Assert.Null(modelsList[0].AgoAobj);

        }
    }


Read more here: https://stackoverflow.com/questions/68463765/why-ef-core-automatically-load-related-entities-when-property-referring-to-the-e

Content Attribution

This content was originally published by Aleksey at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: