title: How to iterate through entities in EF Core migration?
body: <p>I am retrofitting <em>Identity</em> into an existing project. I already had <code>Users</code>, <code>Roles</code>, and <code>UserRoles</code> tables, so it's mainly a matter or adjusting the table and column names before actually adding <em>Identity</em> classes, so they &quot;take over&quot; those tables.</p>
  <p>The problem I have is as following. <code>UserEntity.Id</code> is a <code>Guid</code>, so I need to inherit <code>UserEntity</code> from <code>IdentityUser&lt;Guid&gt;</code>. But <code>RoleEntity.Id</code> is a <code>long</code>. <em>Identity</em> has that strange limitation, that <code>User.Id</code> and <code>Role.Id</code> types must match - at least when used in <code>AddIdentity&lt;&gt;</code> extension method. So I need to change the type of <code>RoleEntity.Id</code> to be <code>Guid</code>. And as I already have a number of users with roles, I have to adjust <code>UserRoles</code> table.</p>
  <p>Now, creating new set of <em>Id</em>s for <code>Roles</code> is not a problem, they are seeded, so I merely created a new column <code>Roles.NewId</code> of type <code>Guid</code> and filled it with some random values. I also created a corresponding column <code>UserRoles.NewRoleId</code> (I will rename them in another migration before applying <em>Identity</em> so they match it). What I want is when <em>this particular</em> migration runs, the values from <code>Roles.NewId</code> are copied to <code>UserRoles.NewRoleId</code>, correspondingly to the existing allocations.</p>
  <p>The SQL command could look like</p>
  <pre><code>UPDATE UserRoles U SET NewRoleId = (SELECT NewId FROM Roles WHERE Roles.Id = U.RoleId)
  </code></pre>
  <p>But I am using in-memory database (<em>SQLite</em>) for testing and <em>MariaDb</em> in production, so the SQL might not match. I already had some problems due to this setup, but there is no in-memory provider for <em>MariaDb</em>. Thus I would feel safer if I could insert the following loop somewhere:</p>
  <pre><code>foreach (var ur in UserRoles)
  {
    ur.NewRoleId = Roles.First(r =&gt; r.Id == ur.RoleId).NewId;
  }
  Save();
  </code></pre>
  <p>Now:</p>
  <ol>
  <li>Where can I insert that loop, so it only gets executed after this migration, and not after every single one?</li>
  <li>How to handle the case that in the very next migration I will rename some columns, and later on I will drop the old <code>Id</code> and <code>RoleId</code> columns?</li>
  </ol>