public static async Task InsertUpdateOrDeleteGraphAsync(BloggingContext context, Blog blog) { var existingBlog = await context.Blogs .Include(b => b.Posts) .FirstOrDefaultAsync(b => b.BlogId == blog.BlogId); if (existingBlog == null) { context.Add(blog); } else { context.Entry(existingBlog).CurrentValues.SetValues(blog); foreach (var post in blog.Posts) { var existingPost = existingBlog.Posts .AsQueryable() .FirstOrDefaultAsync(p => p.PostId == post.PostId); if (existingPost == null) { existingBlog.Posts.Add(post); } else { context.Entry(existingPost).CurrentValues.SetValues(post); } } foreach (var post in existingBlog.Posts) { if (!blog.Posts.Any(p => p.PostId == post.PostId)) { context.Remove(post); } } } await context.SaveChangesAsync(); }
private static async Task IsItNewAsync() { Console.WriteLine(); Console.WriteLine("Show entity-specific check for key set:"); await using (var context = new BloggingContext()) { var blog = new Blog { Url = "http://sample.com" }; // Key is not set for a new entity Console.WriteLine($" Blog entity is {(IsItNew(blog) ? "new" : "existing")}."); context.Add(blog); await context.SaveChangesAsync(); // Key is now set Console.WriteLine($" Blog entity is {(IsItNew(blog) ? "new" : "existing")}."); } Console.WriteLine(); Console.WriteLine("Show general IsKeySet:"); await using (var context = new BloggingContext()) { var blog = new Blog { Url = "http://sample.com" }; // Key is not set for a new entity Console.WriteLine($" Blog entity is {(IsItNew(context, (object)blog) ? "new" : "existing")}."); context.Add(blog); await context.SaveChangesAsync(); // Key is now set Console.WriteLine($" Blog entity is {(IsItNew(context, (object)blog) ? "new" : "existing")}."); } Console.WriteLine(); Console.WriteLine("Show key set on Add:"); await using (var context = new BloggingContext()) { var blog = new Blog { Url = "http://sample.com" }; // Key is not set for a new entity Console.WriteLine($" Blog entity is {(IsItNew(context, (object)blog) ? "new" : "existing")}."); context.Add(blog); // Key is set as soon as Add assigns a key, even if it is temporary Console.WriteLine($" Blog entity is {(IsItNew(context, (object)blog) ? "new" : "existing")}."); } Console.WriteLine(); Console.WriteLine("Show using query to check for new entity:"); await using (var context = new BloggingContext()) { var blog = new Blog { Url = "http://sample.com" }; Console.WriteLine($" Blog entity is {(IsItNewAsync(context, blog) ? "new" : "existing")}."); context.Add(blog); await context.SaveChangesAsync(); Console.WriteLine($" Blog entity is {(IsItNewAsync(context, blog) ? "new" : "existing")}."); } }