public static void AttachAndMovePosts(Blog efBlog, List <Post> Posts) { using (var context = new AnotherBlogContext()) { try { context.Configuration.AutoDetectChangesEnabled = false; context.Blogs.Attach(efBlog); Posts.ForEach(p => { context.Posts.Attach(p); if (p.Title.StartsWith("Entity Framework:")) { context.Entry(p).Property(p2 => p2.Title).CurrentValue = p.Title.Replace("Entity Framework:", "EF:"); context.Entry(p).Reference(p2 => p2.Blog).CurrentValue = efBlog; } }); context.SaveChanges(); } finally { context.Configuration.AutoDetectChangesEnabled = true; } } }
public static void T5D4() { using (var context = new AnotherBlogContext()) { var post = context.Posts.First(p => p.BlogId == 1); post.BlogId = 2; var blog2 = context.Blogs.Find(2); } }
public static void T5D1() { using (var context = new AnotherBlogContext()) { var post = context.Posts.Single(p => p.Title == "My First Post"); post.Title = "My Best Post"; context.SaveChanges(); } }
public static void T5D3() { using (var context = new AnotherBlogContext()) { context.Blogs.Load(); var post = context.Posts.Single(p => p.Title == "My First Post"); Console.WriteLine(context.Entry(post).State); //或者 var entry = context.Entry <Post>(post); Console.WriteLine(entry.State); } }
public static void AddPosts(List <Post> Posts) { using (var context = new AnotherBlogContext()) { try { context.Configuration.AutoDetectChangesEnabled = false; Posts.ForEach(p => context.Posts.Add(p)); } finally { context.Configuration.AutoDetectChangesEnabled = true; } context.SaveChanges(); } }