//A common pattern for some applications is to either Add an entity as new (resulting in a database insert) or Attach an entity as existing and mark it as //modified (resulting in a database update) depending on the value of the primary key. For example, when using database generated integer primary //keys it is common to treat an entity with a zero key as new and an entity with a non-zero key as existing. This pattern can be achieved by setting the //entity state based on a check of the primary key value. For example:
//You can change the state of an entity that is already being tracked by setting the State property on its entry. For example:
var existingBlog = new Blog { BlogId = 1, Name = "ADO.NET Blog" };
using (var context = new BloggingContext())
{
context.Blogs.Attach(existingBlog);
context.Entry(existingBlog).State = EntityState.Unchanged;
// Do some more work...
context.SaveChanges();
}
// Attaching an existing but modified entity to the context
If you have an entity that you know already exists in the database but to which changes may have been made then you can tell the context to attach the entity and set its state to Modified. For example:
var existingBlog = new Blog { BlogId = 1, Name = "ADO.NET Blog" };
using (var context = new BloggingContext())
{
context.Entry(existingBlog).State = EntityState.Modified;
// Do some more work...
context.SaveChanges();
}
Update Detached entity in EF 6
Blog detachedBlog =newBlog(){Id=1,Name="New Blog Again"};using(var ctx =newBlogDBEntities()){
ctx.Entry(detachedBlog).State=EntityState.Modified;
ctx.SaveChanges();}