Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
573 views
in Technique[技术] by (71.8m points)

entity framework - Programmatic data transformation in EF5 Code First migration

Is it possible to do any type of programmatic data transformation in Entity Framework 5 Code First migrations?

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.

Example

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:

  • 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.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should use db 'initializer' for what you want - and/ore 'Seed' of a sort (as to where to inject into the EF flow).

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

Migration should go first, and db 'creation' kind of doesn't make much sense, except for seeding.

You override Seed (you created) to put any db handling there - you have the DbContext exposed - and you can also call SqlQuery if needed.


How to create initializer to create and migrate mysql database?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...