在EF Code First迁移中使用自定义逻辑 [英] Use custom logic in EF Code First migration
问题描述
我有一个包含一定数量数据的现有数据库(即DB不为空)。现在,我决定加密一些敏感数据。我有一列 TemplateBlocks:string
。我要用新列 TemplateBlocksEnc替换它:byte []
,并且我确实正确地更改了代码优先模型。然后我产生了迁移并...卡住了!
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.
推荐答案
您可以使用 Sql
和transact-sql:
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() { /* ... */ }
}
您还可以创建Transact-sql版本的加密或使用sql标准加密。
you also have the create a Transact-sql version of the encryption or use sql standard encryption.
ufn可以创建调用n Sql
。
ufn can be created with n Sql
call.
这篇关于在EF Code First迁移中使用自定义逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!