简体   繁体   English

在Entity Framework迁移期间使用c#转换数据

[英]Transform data using c# during Entity Framework migration

Is it possible to transform data stored in a column using a calculation performed in c# during an Entity First database migration? 在Entity First数据库迁移期间,是否可以使用c#中执行的计算来转换存储在列中的数据?

Currently, I have a column named Content of type nvarchar . 当前,我有一列名为Contentnvarchar类型的列。 I'd like to replace it with a column named ContentBinary of type varbinary , copying the content of each row in the process, but also transforming the content. 我想将其替换为varbinary类型的名为ContentBinary的列,在此过程中复制每一行的内容,同时还要转换内容。

Specifically, I want to convert the string to a UTF-8 encoding and then compress it. 具体来说,我想将字符串转换为UTF-8编码,然后对其进行压缩。

I know that the DbMigration class allows for transformation / data motion using the Sql*() methods, but those methods appear to require all the transformation logic to be in SQL. 我知道DbMigration类允许使用Sql *()方法进行转换/数据移动,但是这些方法似乎要求所有转换逻辑都在SQL中。 I think that would require the compression logic to be duplicated as a stored procedure in SQL Server, which would double the effort required and lead to the potential for inconsistencies over just using the custom c# compression routine directly. 我认为这将需要将压缩逻辑复制为SQL Server中的存储过程,这将使所需的工作量加倍,并导致直接使用自定义c#压缩例程时可能会出现不一致的情况。

I'd like to be able to iterate through all the rows, read each Content value, apply the transformation in C#, and then write it to ContentBinary . 我希望能够遍历所有行,读取每个Content值,在C#中应用转换,然后将其写入ContentBinary

I think this may need to happen as part of the migration transaction for consistency but also because only Content will exist before the migration and only ContentBinary will exist afterward. 我认为这可能需要在迁移事务中进行以保持一致性,而且还因为在迁移之前仅存在Content ,而在迁移之后仅ContentBinary I assume that rules out opening a separate database connection during the migration. 我假设排除在迁移期间打开单独的数据库连接的可能性。 However, if there is a way to access the connection being used for the migration transaction, perhaps that would be enough. 但是,如果有一种方法可以访问用于迁移事务的连接,那么可能就足够了。

you can use the AddOrUpdate method like the following 您可以使用如下所示的AddOrUpdate方法

context.TableName.AddOrUpdate(x=> x.ID, collection);

where the collection is the table itself after apply transforming 应用转换后,集合是表本身的位置

if you provided some code in your question may be I could be more specific. 如果您在问题中提供了一些代码,可能会更具体。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM