efcore icon indicating copy to clipboard operation
efcore copied to clipboard

OnModelCreating is called twice when adding a new migration

Open t-dambacher opened this issue 3 years ago • 1 comments

Hello,

I'm trying to add a new migration, through Visual Studio's Package Manager Console :

Add-Migration Tests

The OnModelCreating method is than called twice on my DbContext, instead of only once as it was previously in v5.0.10:

public class TestContext : DbContext
{
    private static readonly object locker = new();
    private static int callCounts = 0;

    public TestContext(DbContextOptions<TestContext> options)
        : base(options)
    { }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        lock (locker)
        {
            if (callCounts != 0)
            {
                throw new InvalidOperationException();
            }

            callCounts++;

            modelBuilder.Entity<Foo>().HasKey(b => b.Id);
            modelBuilder.Entity<Foo>().ToTable("foo");
        }
    }
}

This is especially an issue to me, as data are now seeded twice instead of only once. We could change some things to make it work though, but it's a clear regression.

The issue has been introduced in v6.0-preview.4, the previous ones work as expected.

Include your code

See this little project to reproduce the issue.

Include provider and version information

EF Core version: starting from v6.0 preview.4 but still exists in v6.0 RC 1 Database provider: Microsoft.EntityFrameworkCore.SqlServer Target framework: .NET 6.0 RC1 Operating system: Windows 10 Enterprise, version 2004, build 19041.1237 IDE: Visual Studio 2022 17.0 Preview 4.1

t-dambacher avatar Sep 27 '21 14:09 t-dambacher

@t-dambacher OnModelCreating is not an appropriate place for such a hook. There are several reasons why EF Core may need to build the model more than once when running an application. For example, the model will be built again whenever EF needs to create a new internal service provider for the context instance.

@AndriySvyryd @bricelam This happens because we now build the model twice inside AddMigration. Once when creating the context instance, and then again later when asking for the scaffolder. I wonder if we need to build the model twice?

ajcvickers avatar Sep 28 '21 17:09 ajcvickers