EF5 Code First迁移中的程序化数据转换 [英] Programmatic data transformation in EF5 Code First migration
问题描述
是否可以在Entity Framework 5 Code First迁移中进行任何类型的程序化数据转换?
Is it possible to do any type of programmatic data transformation in Entity Framework 5 Code First migrations?
有一个 Sql ()执行查询的方法,但是它的返回类型为void,并且我看不到任何获取执行的查询结果的方法。
There is an Sql() method to execute queries, but it has return type void and I don't see any way to get the results of the queries I perform.
示例
我有表 Recipe 与 Ingredient 有一对多关系。由于各种原因,我想将其转换为Ingredients JSON字符串属性。我能想到的唯一方法是这样的:
I have table Recipe with one-to-many relationship to Ingredient. For various reasons I want to convert this to a Ingredients JSON string property instead. The only approach I can think of is something like this:
- 创建新列 IngredientsJson
- 对于每个食谱,查询其成分,以编程方式构造JSON字符串,然后插入新列中。
- 将旧表 Ingredient 放下。
- Create new column IngredientsJson
- For each recipe, query its ingredients, construct a JSON string programmatically and insert into the new column.
- Drop the old table Ingredient.
推荐答案
您应将db'initializer'用于所需的内容-和/或'Seed (关于在哪里注入EF流)。
You should use db 'initializer' for what you want - and/ore 'Seed' of a sort (as to where to inject into the EF flow).
您可以>使用自定义的< 初始化器
-来执行此操作,两者均由Db创建。 。and Migrate 。它不是剪切和粘贴的解决方案,但大多数情况下都可以使用(这是个快速解决问题的方法,您需要稍作调整,下面有一些修复程序)。
You can > take a look at this post with a customized < initializer
- that performas both Db Create... and Migrate. It's not cut and paste solution, but mostly works (it was just a fast go at the problem, you'd need to adjust a bit, it has couple fixes below).
MigrateDatabaseToLatestVersion
仅分配迁移部分-您需要种子
-暴露-或手动包裹该部分(要点是针对不同情况进行检查-即何时参与迁移-或播种)。
MigrateDatabaseToLatestVersion
dose only the migration part - and you need seed
-ing exposed - or manually wrap that part (the main point is in 'checks' done for different situations - i.e. when to 'engage' into migration - or seeding).
应该先进行迁移,而除了种子播种外,db creation的意义不大。
Migration should go first, and db 'creation' kind of doesn't make much sense, except for seeding.
您覆盖了种子
(您创建的)以将所有数据库处理放在那里-您拥有 DbContext
公开-并且,如果需要,您还可以调用 SqlQuery
。
You override Seed
(you created) to put any db handling there - you have the DbContext
exposed - and you can also call SqlQuery
if needed.
这篇关于EF5 Code First迁移中的程序化数据转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!