Which is the good way to update object in EF6

Posted by TrieuH on Stack Overflow See other posts from Stack Overflow or by TrieuH
Published on 2014-06-06T02:58:18Z Indexed on 2014/06/06 3:24 UTC
Read the original article Hit count: 163

Filed under:

I have searched and find 2 way to update object in EF

var attachedEntity = _context.EntityClasses.Local.First(t => t.Id == entity.Id);
  //We have it in the context, need to update.
  if (attachedEntity != null)
  {
     var attachedEntry = _context.Entry(attachedEntity);
     attachedEntry.CurrentValues.SetValues(entity);
  }
  else
  {
  ////If it's not found locally, we can attach it by setting state to modified.
  ////This would result in a SQL update statement for all fields
  ////when SaveChanges is called. 
  var entry = _context.Entry(entity);
  entry.State = EntityState.Modified;
  }
  _context.SaveChanges();

And other way is seem more easy

 var entity = _context.EntityClasses.FirstOrDefault(t => t.Id == entity.Id);
    _context.Entry(entity ).EntityState.Modified
    _context.SaveChanges();

What is best way to update object? NOTE: the performence is importance with me

© Stack Overflow or respective owner

Related posts about entity-framework