A
A
Andrew2016-05-29 04:30:28
ASP.NET
Andrew, 2016-05-29 04:30:28

How to perform Entity framework migration with data migration?

The bottom line is this: there used to be (and still is) a table with workers (without the right to access the server) and several more tables with users (managers and other management personnel) and their roles, which are created through ASP Net Identity. Several tables are tied to the workers.
Now you need to transfer the workers to the table with users.
I use EF Migration, with it the code for migration is automatically generated, and in the middle of this code (after the tables are created / updated and before the tables with workers and other things are deleted) I try to actually perform the data migration itself. Those. (simplified) something like this:

public override void Up()
{
       //Тут какой то код, обновляющий структуру БД
       using (var db = new CwDb())
            {
                const string getWorkersCommand = "Select * from workers";
                ...
                var workers = db.Database.SqlQuery<Worker>(getWorkersCommand);
                ...
                var userManager = new ApplicationUserManager(new UserStore<User>(db));
                var roleManager = new ApplicationRoleManager(new RoleStore<Role>(db));

                foreach (var worker in workers)
                {
                    var newWorker = new User()
                    {
                        ...
                    };
                    var result = userManager.Create(newWorker);

               // Потом для каждого созданного воркера обновляем связи в связанных таблицах

                db.SaveChanges();
            }
       //Тут какой то код, обновляющий структуру БД

Actually, this option does not work (which is expected), it throws an exception:
The underlying context model "CwDb" has changed since the database was created. Consider updating the database with Code First Migrations ( go.microsoft.com/fwlink/?LinkId=238269).

It seems like there is a special method in migrations, Sql (), but it does not return anything with which it would be possible to do what I wrote above. Perhaps I would write everything I need in SQL and just do it through Sql(), but how users are generated in Asp.Net Identity is not entirely clear, in particular Id, Security Stamp.
In general, the question is how to make the correct data migration in the described case? I would be glad for a hint.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
#
#algooptimize #bottize, 2016-05-29
@user004


Questions About Using EF
Questions about how to use EF can be asked on Stack Overflow using the entity-framework tag.
EF Team

M
MIsternik, 2016-05-29
@MIsternik

and the DbMigrationsConfiguration.Seed method is not suitable?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question