The project is ASP.NET Core MVC, .NET 6. I'm trying to seed a role if it's not there yet and create a user that will have this role. I tried every way to twist the code and it doesn't work. When I run the app for the first time, the following error appears on the line where the user is added to the role:
Microsoft.EntityFrameworkCore.DbUpdateException: 'An error occurred while saving the entity changes. See the inner exception for details.'
SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_AspNetUserRoles_AspNetUsers_UserId". The conflict occurred in database "ViewMovies", table "dbo.AspNetUsers", column 'Id'. The statement has been terminated.
Then when I check the database the new role is created, but the user is not.
This all happens in Program.cs. Here I create scope and use it to get role manager and user manager. Then, if the role does not exist, create it and a new user. After that add the new role to the new user.
var app = builder.Build();
var scope = app.Services
.GetService<IServiceScopeFactory>()
?.CreateScope();
if (scope is not null)
{
using (scope)
{
var roleManager = scope
.ServiceProvider
.GetService<RoleManager<IdentityRole>>();
var userManager = scope
.ServiceProvider
.GetRequiredService<UserManager<User>>();
Task
.Run(async () =>
{
if (await roleManager.RoleExistsAsync("test"))
{
return;
}
var role = new IdentityRole { Name = "test" };
await roleManager.CreateAsync(role);
const string testEmail = "test@role.com";
const string testPassword = "test123";
var user = new User
{
Email = testEmail,
UserName = testEmail
};
await userManager.CreateAsync(user, testPassword);
await userManager.AddToRoleAsync(user, role.Name);
})
.GetAwaiter()
.GetResult();
}
}
I have registered these services:
builder.Services.AddDefaultIdentity<User>()
.AddRoles<IdentityRole>()
.AddRoleManager<RoleManager<IdentityRole>>()
.AddEntityFrameworkStores<ViewMoviesDbContext>();
The problem was in the data I was creating for the new user. The password was not valid according to the password restrictions that were set in the services. The password test123
does not contain capital letters and non-alphanumeric characters, which are required by default. Changing it to Test123+
solved the problem.