Skip to content

Revisit model-snapshot for perf #18620

Open

Description

@ajcvickers

At the beginning of EF Core we decided that we would use the fluent API in model snapshots rather than designing a new serialization format. (In other words, the fluent API is the way to serialize the model.) However, this can lead to a lot of code compiled for big models and when the number of migrations build up. See, for example, #18618.

We should consider:

Activity

  1. added this to the Backlog milestone on Oct 28, 2019
  2. AndriySvyryd commented on Oct 30, 2019

    @AndriySvyryd
    Member

    Note that this will likely mean that snapshots will need to be updated for major version upgrades and possibly minor ones. So we should consider #18557 at the same time

  3. bricelam commented on Nov 1, 2019

    @bricelam
    Contributor

    Another idea I has was to only put the store model in the *.Designer.cs files, but this doesn't work since we need the full model when removing a migration.

  4. self-assigned this
    on Nov 5, 2019
  5. ajcvickers commented on Oct 28, 2021

    @ajcvickers
    ContributorAuthor

    We believe this is best handled by squashing migrations: #2174

  6. removed this from the Backlog milestone on Oct 28, 2021
  7. ajcvickers commented on Mar 12, 2023

    @ajcvickers
    ContributorAuthor

    Re-open to consider using the relational model.

  8. added this to the Backlog milestone on Mar 16, 2023
  9. Tasteful commented on Mar 11, 2025

    @Tasteful
    Contributor

    I was trying to work around this in our product that have ~440 migrations and we can't squash them into a single to get a fresh start because the product is installed on-premises at customer and different customer is in different stage of upgrades in versioning.

    I come up to the solution where I created a MSBuild task that extracting the attributes from the *.Designer.cs files and generated a new file. Then I adding a targets file that excluding all the *.Designer.cs files and including the generated file. This somehow is working in many cases but some CreateIndexOperations will add an filter [Id] IS NOT NULL even on non-nullable properties and this does not happen when running the original code.

    The generated file does not contain the BuildTargetModel file where all the metadata about the model at that time the model was created is ignored, this reduced the size for the built assembly from 32 MB to 2 MB and build time from 2 minutes and 30 seconds to 8 seconds so that is a good improvements in speed.

    Does it exists any information about how the model in BuildTargetModel is used during migration up command?

    Should it work to run the migrations up command without the model in BuildTargetModel ?

  10. bricelam commented on Mar 11, 2025

    @bricelam
    Contributor

    Does it exists any information about how the model in BuildTargetModel is used during migration up command?

    This answer is old and there are probably more cases now, but it should give you an idea of how the model is used..

  11. Tasteful commented on Mar 12, 2025

    @Tasteful
    Contributor

    Does it exists any information about how the model in BuildTargetModel is used during migration up command?

    This answer is old and there are probably more cases now, but it should give you an idea of how the model is used..

    This was what I needed to be able to discard this idea, but I investigated how the migrations happens inside EFCore and this is the new working solutions, sharing if anyone else have the same need.

    Part 1:

    First I created a new class library Company.Application.Migrations.Archive that haven't any reference to the original code and having this in my csproj file

    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <TargetFramework>net9.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
        <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
      </PropertyGroup>
    
      <ItemGroup>
        <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="9.0.0" PrivateAssets="All" />
      </ItemGroup>
     
    </Project>

    Then I moved all migrations files into this project, the designer file have a reference to the type of the db context so I created a new db context with the same name in this assembly as below.

        internal class CompanyDbContext : DbContext, ICurrentDbContext
        {
            DbContext ICurrentDbContext.Context => this;
        }

    Also created a simple way to create the db context with an accessor class

        public static class ArchivedDbContextAccessor
        {
            public static ICurrentDbContext GetArchivedDbContext => new CompanyDbContext();
        }

    A lot of migrations have still references in usings to namespaces in the main application but was not using any classes in them so created a large file as

    namespace Company.Application.Events.WebHooks
    {
        class Dummy { }
    }
    
    namespace Company.Application.Products.Data
    {
        class Dummy { }
    }
    
    namespace Company.Application.Products.Excel
    {
        class Dummy { }
    }
    
    namespace Company.Application.Security
    {
        class Dummy { }
    }
    namespace Company.Application.Security.OAuth
    {
        class Dummy { }
    }
    
    namespace Company.Auditing
    {
        class Dummy { }
    }

    This project is now building and a NuGet packages is created.

    Part 2:

    In the main project I adding a package reference to the NuGet package from part 1, then I creating a decorator that wrapping the default IMigrationsAssembly as the following that wrapping the current assembly with the archived assembly and running all the migrations. For service decoration I using something similar to https://github.com/khellang/Scrutor but with attributes.

    [ServiceDecorator(typeof(IMigrationsAssembly))]
    internal class MigrationsAssemblyDecorator : IMigrationsAssembly
    {
        private readonly IMigrationsAssembly _archiveMigrationAssembly;
        private readonly IMigrationsAssembly _parent;
    
        public IReadOnlyDictionary<string, TypeInfo>? _migrations = default;
        public IReadOnlyDictionary<string, TypeInfo> Migrations
        {
            get
            {
                return _migrations ??= _archiveMigrationAssembly.Migrations
                    .Concat(_parent.Migrations)
                    .ToDictionary()
                    .AsReadOnly();
            }
        }
        public ModelSnapshot ModelSnapshot => _parent.ModelSnapshot;
        public Assembly Assembly => _parent.Assembly;
    
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "EF1001:Internal EF Core API usage.", Justification = "<Pending>")]
        public MigrationsAssemblyDecorator(
            IMigrationsAssembly parent,
            IMigrationsIdGenerator idGenerator,
            IDiagnosticsLogger<DbLoggerCategory.Migrations> logger)
        {
            var currentContext = Archive.ArchivedDbContextAccessor.GetArchivedDbContext();
    
            var obuilder = new DbContextOptionsBuilder<CompanyDbContext>();
            var sbuilder = new SqlServerDbContextOptionsBuilder(obuilder);
            sbuilder.MigrationsAssembly(currentContext.Context.GetType().Assembly);
    
            var archiveOptions = obuilder.Options;
            _archiveMigrationAssembly = new MigrationsAssembly(
                currentContext,
                archiveOptions,
                idGenerator,
                logger);
            _parent = parent;
        }
    
        public Migration CreateMigration(TypeInfo migrationClass, string activeProvider)
        {
            return _parent.CreateMigration(migrationClass, activeProvider);
        }
    
        public string FindMigrationId(string nameOrId)
        {
            return
                _archiveMigrationAssembly.FindMigrationId(nameOrId)
                ?? _parent.FindMigrationId(nameOrId);
        }
    }

    Now, when using the IMigrationsAssembly the methods have access to migrations from the class library from the NuGet package and the migrations in the main assembly.

  12. added theissue type on Jun 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions