I have a new ASP.Net Core website that uses an existing database, to which I have added ASP.Net Core Identity for user management.
Since there is an existing user table, I simply added the which I have properly added the ASP.Net identity columns.
The additional columns in the existing table are in my IdentityUser-derived class. The site logic works well when I create new users, as well as logging in, logging out, and the like.
The problem is that all of the existing 'user' records (which I will call MyUser) have blank Core Identity fields, and thus are invisible to the identity system calls.
I would like to write a utility that goes through the existing MyUser records, and if the AspIdentityId field is null, set it up as a record manageable by the Identity subsystem.
I'm essentially looking for the 'Create' call, but I can't use UserManager.
CreateAsync because this creates a new record in the table, it doesn't update an existing one.
I do have two DB contexts (IdentityDBContext and OriginalDBContext), so if there is something that allows me to generate the field data, I can then add this to the columns in the table for the associated record.
Ok, I got this to work, not entirely sure why it works, seems like the AspIdentity fields are populated before they are committed. I have only added the specific changes that were the crux of the question, the DI, setup of the contexts, etc are elsewhere in the project.
Essentially, for each 'domain' record, I create a new ApplicationUser (IdentityUser-derived) record, and add the values for the custom fields in the domain record into the ApplicationUser record. Once this object is created, it has the necessary Asp.Net Identity fields already populated. I then get those fields and populate them back onto the domain specific record, then I save this. Once that is done, I re-find the record (this may not be necessary), and add the password based on the plain text password already in the domain record.
var clients = new List<Client>(myService.myContext.Clients);
foreach (var client in clients)
{
var user = new ApplicationUser // Derived from IdentityUser
{
UserID = client.UserID,
FirstName = client.FirstName,
LastName = client.LastName,
UserName = client.UserName,
PhoneNumber = client.Phone,
Email = client.Email // Other fields omitted for brevity.
};
var idUser = user as IdentityUser;
client.AspIdentityId = user.Id;
client.ConcurrencyStamp = user.ConcurrencyStamp;
client.NormalizedEmail = user.NormalizedEmail;
client.NormalizedUserName = user.NormalizedUserName;
client.PasswordHash = user.PasswordHash;
client.SecurityStamp = user.SecurityStamp;
myService.myContext.SaveChanges();
// Can we just use the 'user' object here?
var newUser = await myService.UserManager.FindByIdAsync(client.AspIdentityId);
var result = await myService.UserManager.AddPasswordAsync(newUser, client.Password);
}
Hope this helps someone, this was important to me to get done this way.