Entity Framework Core 2.2:禁用特定实体的迁移

Entity Framework Core 2.2 : Disable migrations for specific entities

我正在尝试在已创建数据库的现有系统上构建一个 aspnetcore 应用程序,我将在其上添加一些表。

我对数据库进行了逆向工程以将现有表作为实体添加到我的应用程序中,并且我编写了自己的实体以供稍后添加。最后,所有实体都添加到单个 DbContext。

我的需求如下:

注意:我不想碰生成的迁移代码。

有没有合适的方法来处理这种情况?

Is there a proper way to handle this scenario?

编辑迁移代码是处理这种情况的正确方法。

或者,您可以创建一个带有迁移的 DbContext,其中仅包含映射到您要使用迁移管理的表的实体。然后使用所有用于读取和写入数据库的实体创建另一个 DbContext。

请注意,如果您不想在数据库中添加 真实 引用表的外键,您的迁移上下文可能缺少导航属性,仅包含相应的外键属性不受您的迁移控制。

如果在 Add-Migration 操作之后通过检查命令行参数调用实体生成器,您可以忽略该实体;

public void Configure(EntityTypeBuilder<YourEntity> builder)
{
    //all properties to be mapped...

    //ignored when adding a new migration
    builder.HasOne(p => p.EntityDetail)
        .WithOne()
        .HasForeignKey<Entity>(x => x.Id)
        .IsRequired(false);

    if (MigrationHelper.IsMigrationOperationExecuting())
        builder.Ignore(x => x.EntityDetail);
}

public static class MigrationHelper
{
    public static bool IsMigrationOperationExecuting()
    {
        var commandLineArguments = Environment.GetCommandLineArgs();
        string[] orderedMigrationArguments = { "migrations", "add" };

        for (var i = 0; i <= commandLineArguments.Length - orderedMigrationArguments.Length; i++)
        {
            if (commandLineArguments.Skip(i).Take(orderedMigrationArguments.Length).SequenceEqual(orderedMigrationArguments))
                return true;
        }

        return false;
    }
}