public async Task <DbResponse <CustomRole> > Add(CustomRoleVm roleVm) { try { if (context.CustomRoles.Any(x => x.Name == roleVm.Name)) { return(new DbResponse <CustomRole> { ErrorMessage = "Роль с таким названием уже существует" }); } var customRole = new CustomRole() { Name = roleVm.Name, Description = roleVm.Description, }; var appRoles = roleVm.AppRoles.Where(x => x.IsSelected).ToList(); customRole.AppRoleCustomRoles = roleVm.AppRoles.Where(x => x.IsSelected) .Select(x => new AppRoleCustomRole { AppRoleId = x.Id, CustomRoleId = customRole.Id }).ToList(); context.CustomRoles.Add(customRole); await context.SaveChangesAsync(); return(new DbResponse <CustomRole> { Message = "Роль создана", Response = customRole }); } catch (Exception ex) { // log.. return(new DbResponse <CustomRole> { ErrorMessage = "Произошла ошибка при создании роли" }); } }
public static async Task Seed(this DataContext context, UserManager <AppUser> userManager, RoleManager <AppRole> roleManager) { if (await roleManager.FindByNameAsync("Admin") == null) { await roleManager.CreateAsync(new AppRole("Admin", "Полный доступ")); } if (await roleManager.FindByNameAsync("CanApplyRequest") == null) { await roleManager.CreateAsync(new AppRole("CanApplyRequest", "Подача заявок")); } if (await roleManager.FindByNameAsync("CanCreateRequest") == null) { await roleManager.CreateAsync(new AppRole("CanCreateRequest", "Создание заявок")); } if (await roleManager.FindByNameAsync("CanEditRequest") == null) { await roleManager.CreateAsync(new AppRole("CanEditRequest", "Редактирование заявок")); } if (await roleManager.FindByNameAsync("CanViewRequest") == null) { await roleManager.CreateAsync(new AppRole("CanViewRequest", "Просмотр заявок")); } if (context.CustomRoles.FirstOrDefault(x => x.Name == "Администратор") == null) { var adminRole = new CustomRole { Name = "Администратор" }; var appRoleAdmind = context.Roles.FirstOrDefault(x => x.Name == "Admin"); adminRole.AppRoleCustomRoles.Add(new AppRoleCustomRole { AppRoleId = appRoleAdmind.Id, CustomRoleId = adminRole.Id }); context.CustomRoles.Add(adminRole); context.CustomRoles.Add(new CustomRole { Name = "Клиент" }); context.SaveChanges(); } if (!context.Users.Any(u => u.Email == "*****@*****.**")) { var adminUser = new AppUser { UserName = "******", Email = "*****@*****.**" }; await userManager.CreateAsync(adminUser, "admin12345"); await userManager.AddToRoleAsync(adminUser, "Admin"); } }