我可以从 EF Core 迁移访问应用程序设置吗?

Kha*_*ine 5 c# entity-framework-core asp.net-core

我非常需要通过添加 SQL 脚本来手动修改代码优先迁移。脚本并不完全是一个问题,但我还想向其中注入一些将在 appsettings.json 中设置的内容。除了导航到文件路径并手动读取内容之外,是否可以通过其他方式访问此配置?

Bra*_*ang 6

你的意思是你想获取migration.cs文件中的appsettings值吗?

如果这是您的要求,您可以使用ConfigurationBuilder并设置 appsetting.json 路径来读取它。

更多详细信息,您可以参考以下代码:

public partial class Modify5 : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropColumn(
            name: "Msg",
            table: "Logs");

        migrationBuilder.DropColumn(
            name: "Timestamp",
            table: "Logs");

        migrationBuilder.AddColumn<DateTime>(
            name: "CreatedDate",
            table: "Logs",
            nullable: false,
            defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified));

        migrationBuilder.AddColumn<DateTime>(
            name: "CreatedDate2",
            table: "Logs",
            nullable: false,
            defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified));

        migrationBuilder.AddColumn<string>(
            name: "Message",
            table: "Logs",
            nullable: true);

        string re = GetParameters();
        Console.WriteLine("Save");
        Console.WriteLine(re);
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropColumn(
            name: "CreatedDate",
            table: "Logs");

        migrationBuilder.DropColumn(
            name: "CreatedDate2",
            table: "Logs");

        migrationBuilder.DropColumn(
            name: "Message",
            table: "Logs");

        migrationBuilder.AddColumn<string>(
            name: "Msg",
            table: "Logs",
            type: "nvarchar(max)",
            nullable: true);

        migrationBuilder.AddColumn<DateTime>(
            name: "Timestamp",
            table: "Logs",
            type: "datetime2",
            nullable: false,
            defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified));

  
    }

    private static string GetParameters()
    {
        var builder = new ConfigurationBuilder()
                            .SetBasePath(@"the application root path")
                            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

        var val1 = builder.Build().GetSection("AllowedHosts").Value;

        return $"The values of parameters are: {val1}";
    }
}
Run Code Online (Sandbox Code Playgroud)

结果:

在此输入图像描述