如何在Migration类,Up方法中访问EF模型注释?

时间:2018-01-11 15:04:47

标签: .net entity-framework annotations entity-framework-core ef-migrations

如何在Migration类,Up方法中访问EF模型注释?

我的意思是那些注释:

modelBuilder.Entity<Role>().HasAnnotation("constraint1", constraint);

在这种方法中:

public partial class InitialCreate : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
          // how to access annotations? means get value of Role's "constraint1" annotation
    }
}

迁移的构建过程(在其自动化步骤中)可以使用注释(以及其他定义)但是如果您想手动添加/更改迁移代码,则不清楚如何访问元数据。

1 个答案:

答案 0 :(得分:2)

问题在于迁移过程中没有单一模型,或者更确切地说,迁移代表两个模型之间的转换,并且它们都不是当前模型。迁移构建过程使用模型快照和差异来生成迁移命令。

最终您可以尝试从Migration.TargetModel属性获取信息。它在迁移时提供模型的快照,并由相关迁移designer.cs文件中的代码构建。

public partial class InitialCreate : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        // how to access annotations? means get value of Role's "constraint1" annotation
        var annotations = TargetModel.FindEntityType("YourModelNamespace.Role"))
            .GetAnnotations();
        // or
        var constraint1 = TargetModel.FindEntityType("YourModelNamespace.Role"))
            .FindAnnotation("constraint1");
    }
}