private void button2_Click(object sender, EventArgs e) { var post = new Post { Text = "Hello World" }; using (var db = new StackOverflowEntities()) { db.Attach(blog); blog.Posts.Add(post); db.SaveChanges(); } }
private void commitAllPosts_Click(object sender, EventArgs e) { using (var db = new StackOverflowEntities()) { // load existing blog into ChangeTracker var existingBlog = db.Set <Blog>().First(b => b.BlogId == blog.BlogId); // add new posts to tracked Blog entity foreach (var post in blog.Posts) { if (post.PostId == 0) { // this only works if your Post record has a primary key has Identity Specification set to yes existingBlog.Posts.Add(post); } } db.SaveChanges(); } }
private void commitAllPosts_Click(object sender, EventArgs e) { using (var db = new StackOverflowEntities()) { // load existing blog into ChangeTracker (but not efficient) // var existingBlog = db.Set<Blog>().First(b => b.BlogId == blog.BlogId); // make shallow copy of existing blog and attach it Blog existingBlog = new Blog { BlogId = blog.BlogId, Name = blog.Name }; db.Set <Blog>().Attach(existingBlog); // if the root blog record must be updated //db.Entry(existingBlog).State == EntityState.Modified; // add new posts to tracked Blog entity foreach (var post in blog.Posts) { if (post.PostId == 0) { existingBlog.Posts.Add(post); } } db.SaveChanges(); } }