1

How to access the EF model annotations in Migration class, Up method?

I mean those annotations:

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

In this method:

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

Migration's build process (on its automation step) can use annotations (as well as other definitions) but then if you want to manually append/change migration code it is not obvious how to access metadata.

Roman Pokrovskij
  • 9,449
  • 21
  • 87
  • 142
  • What do you mean by "*access* the EF model annotations"? And what do you need them for in the migration code? Feels a bit murky. – Gert Arnold Jan 11 '18 at 15:09
  • Access means get value. What I would do with them - use in migration (e.g. create constraint). – Roman Pokrovskij Jan 11 '18 at 15:10
  • 1
    Correct me if I'm wrong (haven't got much hands-on experience with ef-core + migrations), but shouldn't the migrations code be the result of annotations? – Gert Arnold Jan 11 '18 at 15:19
  • migration first of all is a result of migration build process (it can be automated, and than appended/edited manually). migration's build process (it its automation step) can use annotations (as well as other definitions). – Roman Pokrovskij Jan 11 '18 at 15:42

1 Answers1

2

The problem is that there is no single model during the migration, or more precisely, the migration represents transformation between two models and none of them could be the current. Migration build process uses model snapshots and differences to produce the migration commands.

Eventually you could try getting the information form the Migration.TargetModel property. It provides the snapshot of the model at the time of the migration and is built by the code in the associated migration designer.cs file.

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");
    }
}
Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343
  • This works but only for plain string meta. Therefore https://stackoverflow.com/questions/48216074/how-to-add-the-support-for-structured-annotations-to-the-ef-core-sqlserver-targe – Roman Pokrovskij Jan 11 '18 at 21:31