public static void InsertUpdateOrDeleteGraph(BloggingContext context, Blog blog) { var existingBlog = context.Blogs .Include(b => b.Posts) .FirstOrDefault(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() .FirstOrDefault(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); } } } context.SaveChanges(); }
private static void IsItNew() { Console.WriteLine(); Console.WriteLine("Show entity-specific check for key set:"); 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); context.SaveChanges(); // Key is now set Console.WriteLine($" Blog entity is {(IsItNew(blog) ? "new" : "existing")}."); } Console.WriteLine(); Console.WriteLine("Show general IsKeySet:"); 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); context.SaveChanges(); // Key is now set Console.WriteLine($" Blog entity is {(IsItNew(context, (object)blog) ? "new" : "existing")}."); } Console.WriteLine(); Console.WriteLine("Show key set on Add:"); 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:"); using (var context = new BloggingContext()) { var blog = new Blog { Url = "http://sample.com" }; Console.WriteLine($" Blog entity is {(IsItNew(context, blog) ? "new" : "existing")}."); context.Add(blog); context.SaveChanges(); Console.WriteLine($" Blog entity is {(IsItNew(context, blog) ? "new" : "existing")}."); } }