efcore icon indicating copy to clipboard operation
efcore copied to clipboard

Model is rebuilt when the database root changes

Open koenigst opened this issue 6 months ago • 1 comments

We use the databaseRoot parameter of UseInMemoryDatabase to provide test isolation when using the in-memory provider. Unfortunately setting this parameter leads to a huge performance overhead because the model is rebuilt for every test.

Reproduction steps

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using Xunit;

public sealed class ModelRebuild
{
    [Fact]
    public void NoDatabaseRootInOptions_ModelReused()
    {
        var options1 = new DbContextOptionsBuilder<TestContext>()
            .UseInMemoryDatabase("test1")
            .Options;
        var options2 = new DbContextOptionsBuilder<TestContext>()
            .UseInMemoryDatabase("test2")
            .Options;

        using var context1 = new TestContext(options1);
        using var context2 = new TestContext(options2);

        Assert.Same(context1.Model, context2.Model);
    }

    [Fact]
    public void DatabaseRootSetInOptions_ModelRebuilt()
    {
        var options1 = new DbContextOptionsBuilder<TestContext>()
            .UseInMemoryDatabase("test1", new InMemoryDatabaseRoot())
            .Options;
        var options2 = new DbContextOptionsBuilder<TestContext>()
            .UseInMemoryDatabase("test2", new InMemoryDatabaseRoot())
            .Options;

        using var context1 = new TestContext(options1);
        using var context2 = new TestContext(options2);

        Assert.NotSame(context1.Model, context2.Model);
    }

    private sealed class TestContext(DbContextOptions<TestContext> options) : DbContext(options);
}

EF Core version

Database provider: Microsoft.EntityFrameworkCore.InMemory 8.0.8 Target framework: .NET 8.0 Operating system: Windows 11 22H2 IDE: Visual Studio 2022 (64-bit) 17.10.1

koenigst avatar Aug 20 '24 12:08 koenigst