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.68k stars 3.16k forks source link

Add testing for Find/FindAsync with default QueryTrackingBehavior #32762

Open AceCoderLaura opened 8 months ago

AceCoderLaura commented 8 months ago

Find doesn't respect the QueryTrackingBehavior.

This test fails even though QueryTrackingBehavior is set to NoTrackingWithIdentityResolution (NoTracking also fails)


    public QueryTrackingTests()
    {
        var options = new DbContextOptionsBuilder<PrimaryContext>()
            .UseSqlite($"Filename={_dbname}")
            .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTrackingWithIdentityResolution)
            .Options;
        _context = new PrimaryContext(options);
    }

    [Fact]
    public void FindReturnsAsNoTracking()
    {
        var record = _context.TestItems.Find(_recordKey);
        var reloaded = _context.TestItems.Find(_recordKey);
        Assert.NotSame(record, reloaded);
    }

Full test code here.

The documentation for Find says "If an entity with the given primary key values is being tracked by the context, then it is returned immediately without making a request to the database." But I think this should not apply when QueryTrackingBehavior is set to NoTracking. NoTracking should mean no tracking, but I'm receiving a tracked record.

Include provider and version information

EF Core version: Database provider: Microsoft.EntityFrameworkCore.Sqlite Target framework: net8.0 Operating system: Windows 10 Pro IDE: Rider 2023.3.2

ajcvickers commented 8 months ago

This is by-design. Find is specifically designed for tracking scenarios. Use a query to bring back entities without tracking them.

AceCoderLaura commented 8 months ago

But then why does Find respect the QueryTrackingBehavior when the entity isn't already tracked? (which should be noted is a behaviour that contradicts the documentation, perhaps this is a bug?)

ajcvickers commented 8 months ago

But then why does Find respect the QueryTrackingBehavior when the entity isn't already tracked?

This came as a surprise to us. It's not supposed to be this way, as far as we can remember, but it's possible it never got tested. It would be breaking and have minimal value to change it now, but we should add tests.