问题
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