I need to insert a few seed users into the system. To do so, I have written an ApplicationUserConfiguration class and registered the class in the ApplicationDbContext class's OnModelCreating. The application is working fine for the seed values but there are two issues with my implementation:
Every time when I generate a new migration with the Add-Migration command, I get the users in the Up and Down method of the migration though the users are already inserted in the database for the first time I ran the migration.
When I change the password, the newly changed password is working fine until I create a new migration. Every time when I create a new migration, I get the users in the Up and Down method and when running Update-Database, the passwords are again reset from the migration.
Could you please help me to fix the above-mentioned issues?
public class ApplicationUserConfiguration : IEntityTypeConfiguration<ApplicationUser>
{
public void Configure(EntityTypeBuilder<ApplicationUser> builder)
{
PasswordHasher<ApplicationUser> passwordHasher = new PasswordHasher<ApplicationUser>();
// User1
ApplicationUser user = new ApplicationUser
{
Id = "f3a6223f-ac2d-47d9-87d7-e297ea1b78e4",
ConcurrencyStamp = "f3a6223f-ac2d-47d9-87d7-e297ea1b78e4",
Email = "[email protected]",
NormalizedEmail = "[email protected]",
EmailConfirmed = true,
FirstName = "User1",
LastName = "XYZ",
UserName = "[email protected]",
NormalizedUserName = "[email protected]",
};
user.PasswordHash = passwordHasher.HashPassword(user, "Apple@123");
builder.HasData(user);
// User 2
user = new ApplicationUser
{
Id = "c061e936-bfc7-4b2a-95d1-644f2c19037a",
ConcurrencyStamp = "c061e936-bfc7-4b2a-95d1-644f2c19037a",
Email = "[email protected]",
NormalizedEmail = "[email protected]",
EmailConfirmed = true,
FirstName = "User2",
LastName = "XYZ",
UserName = "[email protected]",
NormalizedUserName = "[email protected]",
};
user.PasswordHash = passwordHasher.HashPassword(user, "Banana@123");
builder.HasData(user);
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.ApplyConfiguration(new ApplicationUserConfiguration());
}
}
CodePudding user response:
Ef core runs configuration and the changes add to migration when every new migration. In your case, i guess passwordHasher
generate password by time so it will generate different hash each time.
You have to assign it statically.
user.PasswordHash = 'hashedPassword'