private async Task RecursiveDeleteCategory(Category currentCategory, EFCoreStoreContext context) { var subCategories = await(from c in context.Categories.AsNoTracking() where c.ParentId == currentCategory.CategoryId select c).ToListAsync(); foreach (var child in subCategories) { await RecursiveDeleteCategory(child, context); } try { using (EFCoreStoreContext dbContex = new EFCoreStoreContext()) { var sroredCategory = await dbContex.Categories.SingleOrDefaultAsync(c => c.CategoryId == currentCategory.CategoryId); if (sroredCategory != null) { Console.WriteLine($"正在删:\t\tName:{currentCategory.Name}\tPath:{currentCategory.Path}"); dbContex.Categories.Remove(sroredCategory); await dbContex.SaveChangesAsync(); } } } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public async Task AddCategories() { var context = new EFCoreStoreContext(); #region 保存 try { var category1 = new Category { Name = "category1", Path = "1", Parent = null }; context.Categories.Add(category1); await context.SaveChangesAsync(); var category2 = new Category { Name = "category2", Path = "1:2", Parent = category1 }; context.Categories.Add(category2); await context.SaveChangesAsync(); var category3 = new Category { Name = "category3", Path = "1:3", Parent = category1 }; context.Categories.Add(category3); await context.SaveChangesAsync(); var category4 = new Category { Name = "category4", Path = "1:3:4", Parent = category3 }; context.Categories.Add(category4); await context.SaveChangesAsync(); var category5 = new Category { Name = "category5", Path = "1:3:5", Parent = category3 }; context.Categories.Add(category5); await context.SaveChangesAsync(); var category6 = new Category { Name = "category6", Path = "6", Parent = null }; context.Categories.Add(category6); await context.SaveChangesAsync(); var category7 = new Category { Name = "category7", Path = "6:7", Parent = category6 }; context.Categories.Add(category7); await context.SaveChangesAsync(); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { context.Dispose(); } #endregion }