在实体框架迁移期间使用c#转换数据 [英] Transform data using c# during Entity Framework migration

查看:109
本文介绍了在实体框架迁移期间使用c#转换数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Entity First数据库迁移期间,是否可以使用c#中执行的计算来转换存储在列中的数据?

Is it possible to transform data stored in a column using a calculation performed in c# during an Entity First database migration?

目前,我有一个名为内容类型为 nvarchar 。我想用 varbinary 类型的名为 ContentBinary 的列替换,复制每行的内容过程,但也转换内容。

Currently, I have a column named Content of type nvarchar. 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.

具体来说,我想将字符串转换为UTF-8编码,然后压缩它。

Specifically, I want to convert the string to a UTF-8 encoding and then compress it.

我知道DbMigration类允许使用Sql *()方法进行转换/数据运动,但这些方法似乎要求所有的转换逻辑都在SQL中。我认为这将需要在SQL Server中将压缩逻辑复制为存储过程,这将使所需的工作量加倍,并导致直接使用自定义c#压缩例程的不一致的可能性。

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. 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.

我想要遍历所有行,读取每个 Content 值,在C#中应用转换,然后将其写入 ContentBinary

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.

我认为这可能需要作为迁移事务的一部分发生,以保持一致性, code>内容将在迁移之前存在,只有 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. 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.

推荐答案

可以使用 AddOrUpdate 方法
像以下

you can use the AddOrUpdate method like the following

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.

这篇关于在实体框架迁移期间使用c#转换数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆