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 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); } }