private static async Task DeleteOrphansSampleAsync(DeleteBehavior deleteBehavior, bool requiredRelationship) { Console.WriteLine($"Test deleting orphans with DeleteBehavior.{deleteBehavior} and {(requiredRelationship ? "a required" : "an optional")} relationship:"); await InitializeDatabaseAsync(requiredRelationship); await using var context = new BloggingContext(deleteBehavior, requiredRelationship); #region DeleteOrphansVariations var blog = await context.Blogs.Include(b => b.Posts).FirstAsync(); var posts = await blog.Posts.AsQueryable().ToListAsync(); DumpEntities(" After loading entities:", context, blog, posts); blog.Posts.Clear(); DumpEntities(" After making posts orphans:", context, blog, posts); try { Console.WriteLine(); Console.WriteLine(" Saving changes:"); await context.SaveChangesAsync(); DumpSql(); DumpEntities(" After SaveChanges:", context, blog, posts); } catch (Exception e) { DumpSql(); Console.WriteLine(); Console.WriteLine($" SaveChanges threw {e.GetType().Name}: {(e is DbUpdateException ? e.InnerException.Message : e.Message)}"); } #endregion Console.WriteLine(); }
private static async Task InitializeDatabaseAsync(bool requiredRelationship) { await using var context = new BloggingContext(DeleteBehavior.ClientSetNull, requiredRelationship); await context.Database.EnsureDeletedAsync(); await context.Database.EnsureCreatedAsync(); context.Blogs.Add(new Blog { Url = "http://sample.com", Posts = new List <Post> { new Post { Title = "Saving Data with EF" }, new Post { Title = "Cascade Delete with EF" } } }); await context.SaveChangesAsync(); }