I have a method which is called in the constructor of my controller Home in the created roles when starting the application and assigned a specific role to a user, it happens that I do not create any record in the db, in addition to debug the code I realize that it skips instructions or simply does not execute them all and it is cut in x instruction (it does not throw me any error) and the application itself keeps working.
My method
private async Task CreateRoles(IServiceProvider serviceProvider)
{
//obtener servicios del role manager
var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var userManager = serviceProvider.GetRequiredService<UserManager<IdentityUser>>();
String[] rolesName = { "Admin", "User" };
foreach (var item in rolesName)
{
var roleExist = await roleManager.RoleExistsAsync(item);
if (!roleExist)
{
await roleManager.CreateAsync(new IdentityRole(item));
}
}
var user = await userManager.FindByIdAsync("027166cf-2757-4f96-9dc1-5d83bb8c0716");
await userManager.AddToRoleAsync(user, "Admin");
}
When executing this method, execute up to this line:
var user = await userManager.FindByIdAsync("027166cf-2757-4f96-9dc1-5d83bb8c0716");
And what follows does not execute it. From time to time when I give it to him repeatedly f5 he finally goes through the missing line, the one that should create my roles with the user but still does not create them in the db.
As there are also times when the program or debugging is cut in this line:
var roleExist = await roleManager.RoleExistsAsync(item);
(without errors, sorry for being foolish with this)
My Home Controller Builder
public HomeController(IServiceProvider serviceProvider)
{
CreateRoles(serviceProvider);
}
Part of my startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
//services.AddDefaultIdentity<IdentityUser>()
// .AddEntityFrameworkStores<ApplicationDbContext>();
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
I am using VS 2017 Community with SQL Server 2008 r2
Does anyone know what this problem is that does not run all the lines of the code and cut before finishing the program? I point out again that it does not give me any error neither the code nor in the application.