Reputation: 23935
Please read the paragraph EDIT2 for the actual state of the question
I am trying to add an initial account to my database while a migration is running, to ensure access to my application.
Unfortunatly the table AspNetUsers
is not changed after the Seed
method is finished and I can't find a proper way to debug for possible errors.
Configuration.cs
internal sealed class Configuration : DbMigrationsConfiguration<ApplicationDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
ContextKey = "Namespace.Models.ApplicationDbContext";
}
protected override void Seed(ApplicationDbContext context)
{
var manager = new UserManager<ApplicationUser>(
new UserStore<ApplicationUser>(
new ApplicationDbContext()));
var user = new ApplicationUser()
{
UserName = "admin",
Email = "admin@admin",
LastName ="lname",
FirstName = "fname"
};
manager.Create(user, @"gibberish");
/* context.SaveChanges(); ?valid */
}
}
After issuing the update-database -force -verbose
command the pm console writes The Seed method is being executed
(free translation from German), but as stated above the table is not updated with a new user.
Where did I go wrong?
EDIT: I just tried the following:
if (!context.Roles.Any(r => r.Name == "Administrator"))
{
var store = new RoleStore<IdentityRole>(context);
var manager = new RoleManager<IdentityRole>(store);
var role = new IdentityRole { Name = "Administrator" };
manager.Create(role);
}
which did work. So a role named Administrator has been created after Update-Database -Force
was issued. The user however, not.
EDIT2:
So apparently I found the culprit.
I was trying to make sure that an admin account was always available. Therefor I tried to add a user username-admin
. However this did not work. After some time I thought about trying it with a different approach and changed the username to username
. Now this did the trick and the user was added and pushed into the role Administrator
.
The question remains: why does it not work adding a user with a special character like -
?
Upvotes: 2
Views: 811
Reputation: 5162
By default, UserName
can only be alphanumeric, i.e. not even an email address is allowed. You need to turn off the validation or implement your own validator (as easily found on SO), e.g.
_userManager = new UserManager<IdentityUser>(_userStore);
_userManager.UserValidator = new UserValidator<IdentityUser>(_userManager) { AllowOnlyAlphanumericUserNames = false };
Upvotes: 3