Skip to content

Commit

Permalink
Refactored photo and roles seeding (#33) (#34)
Browse files Browse the repository at this point in the history
  • Loading branch information
m1adow committed Feb 6, 2023
1 parent 6e6ff87 commit a817110
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions api/webAPI/Extensions/DataBaseExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,27 @@ public static async Task MigrateDataBaseAsync(this IServiceProvider serviceProvi
await context.Database.MigrateAsync();

var roleManager = services.GetRequiredService<RoleManager<AppRole>>();
await roleManager.CreateRolesAsync();
await roleManager.CreateRolesAsync(context);

await context.SyncPhotosAsync(services.GetRequiredService<IPhotoService>());
}

private static async Task CreateRolesAsync(this RoleManager<AppRole> roleManager)
private static async Task CreateRolesAsync(this RoleManager<AppRole> roleManager, IDataContext context)
{
var roles = new AppRole[]
{
new AppRole { Name = "Gamer" },
new AppRole { Name = "Admin" }
};

foreach (var role in context.Roles)
{
if (role != null && !roles.Contains(role))
{
await roleManager.DeleteAsync(role);
}
}

foreach (var role in roles)
{
if (await roleManager.FindByNameAsync(role.Name) is null)
Expand All @@ -42,6 +50,7 @@ private static async Task SyncPhotosAsync(this IDataContext context, IPhotoServi
var photos = await photoService.GetPhotosAsync();
context.Photos.AddRange(photos.Where(photo => context.Photos.All(p => p.Url != photo))
.Select(p => new Photo { Url = p }));
context.Photos.RemoveRange(context.Photos.Where(p => !photos.Contains(p.Url)));
await context.SaveChangesAsync();
}
}

0 comments on commit a817110

Please sign in to comment.