【问题标题】:How can I test if my model has changed and requires a migration?如何测试我的模型是否已更改并需要迁移?
【发布时间】:2022-03-11 18:10:08
【问题描述】:

在开发 dot net 应用程序时,我们会定期对模型进行更改,并且可能让我们的单元测试仅在内存中运行、动态创建的数据库。

一切都可以正常工作,一切都很好,然后我们部署,突然一切停止工作,因为我们忘记了我们需要迁移数据库。

如果模型已更改但它没有针对该更改的迁移,我如何编写将失败的单元测试?

【问题讨论】:

    标签: .net-core entity-framework-core


    【解决方案1】:

    像这样

    using MyProject.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore.Design;
    using Microsoft.EntityFrameworkCore.Migrations.Design;
    using Microsoft.Extensions.DependencyInjection;
    using Shouldly;
    using System.Text.RegularExpressions;
    using System.Threading.Tasks;
    using Xunit;
    
    namespace MyProject.Tests.Migrations
    {
        public class MissingMigrationsTest : MyProjectTestBase
        {
            /// <summary>
            /// Sometimes we change the model, but forget to create a migration for it (with dotnet ef migrations add)
            /// We do this test to detect a missing migration.
            /// </summary>
            /// <returns></returns>
            [Fact]
            public async Task ShouldCreateABlankMigration()
            {
                var db = new MyProjectDbContextFactory();
    
                // Create design-time services
                var serviceCollection = new ServiceCollection();
                serviceCollection.AddEntityFrameworkDesignTimeServices();
                serviceCollection.AddDbContextDesignTimeServices(db);
                var serviceProvider = serviceCollection.BuildServiceProvider();
    
                // Create a migration
                var migrationsScaffolder = serviceProvider.GetService<IMigrationsScaffolder>();
                Microsoft.EntityFrameworkCore.Migrations.Design.ScaffoldedMigration migration = migrationsScaffolder.ScaffoldMigration("test", "MyProject");
    
                var rs = Regex.Replace(migration.MigrationCode, @"\s+", string.Empty);
                //crude but, lets just remove all whitespace, and then check it has a blank Up() function
                rs.Contains("Up(MigrationBuildermigrationBuilder){}").ShouldBeTrue();
            }
    
        }
    }
    

    感谢:https://docs.microsoft.com/nl-be/ef/core/cli/services#using-services 和正则表达式。

    【讨论】:

      猜你喜欢
      • 2013-11-16
      • 1970-01-01
      • 2014-07-01
      • 2018-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-15
      相关资源
      最近更新 更多