Use custom logic in EF Code First migration

狂风中的少年 提交于 2019-12-11 19:06:49

问题


I have an existing Database with a some amount of data (i.e. DB is not empty). Now I made a decision to encrypt some sensitive data. I have a column TemplateBlocks : string. I'm going to replace it with new column TemplateBlocksEnc : byte[] and I did properly changed my Code First model. Then I generated migration and ... stuck!

public partial class EncryptTemplateBlocks : DbMigration
{
    public override void Up()
    {
        AddColumn("dbo.Devices", "TemplateBlocksEnc", c => c.Binary(nullable: true));

        // TODO: read TemplateBlocks data, encrypt, save to new column

        AlterColumn("dbo.Devices", "TemplateBlocksEnc", c => c.Binary(nullable: false));
        DropColumn("dbo.Devices", "TemplateBlocks");
    }

    public override void Down() { /* ... */ }
}

Of course, I do not plan to lose any existing data, I need to read all data from old column, encrypt it, store to newly created column and only then I can drop old column.

Is it possible? I guess that I need somehow to get the current connection/transaction, but I have no idea how to make it.


回答1:


you can use Sql and transact-sql:

public partial class EncryptTemplateBlocks : DbMigration {
public override void Up()
{
    AddColumn("dbo.Devices", "TemplateBlocksEnc", c => c.Binary(nullable: true));

    // TODO: read TemplateBlocks data, encrypt, save to new column
    Sql("UPDATE dbo.Devices SET TemplateBlocksEnc = ufn_Func(TemplateBlocks) WHERE TemplateBlocksEnc IS NULL");

    AlterColumn("dbo.Devices", "TemplateBlocksEnc", c => c.Binary(nullable: false));
    DropColumn("dbo.Devices", "TemplateBlocks");
}

public override void Down() { /* ... */ }
}

you also have the create a Transact-sql version of the encryption or use sql standard encryption.

ufn can be created with n Sql call.



来源:https://stackoverflow.com/questions/24510143/use-custom-logic-in-ef-code-first-migration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!