Best way to update an entity in entity Framework

c# entity-framework

Question

I'm new at entity framework, I was using Nhibernate. In Nhibernate to update an object it's not necesary to pass the id, you just pass the entity and Nhibernate matches the id by it self and update the entity. In EF i'm using this aprouch:

        protected virtual bool UpdateEntity(TEntity entity, int id)
        {
          using (var ctx = new GenericContext())
          {
              var list = ctx.Set<TEntity>().ToList();
              ctx.Entry<TEntity>(ctx.Set<TEntity>  ().Find(id)).CurrentValues.SetValues(entity);
              return ctx.SaveChanges() > 0;
        }
       }

That needs the id to update the entity. Is this the best aprouch? There's some way to update the entity just passing the entity without first finding it?

1
3
3/8/2015 10:23:26 PM

Accepted Answer

It depends if you have auto tracking enabled. By default it is, which means that any entity you retrieve will be stored in the DbContext you used to retrieve it, along with a copy of its original values.

Then if you edit this entity, when you call DbContext.SaveChanges(), EF will go through all your entities, and compare them with their original values, and if any has changed, it will execute an update statement.

So if you both retrieve the Entity, Edit it, and want to save it, all in the scope of the same context. All you have to do is call contxt.SaveChanged() and EF will work out that this entity has been updated. (As long as you have not disabled AutoTracking)

Borrowing from Eriks code:

var ctx = new SchoolDBEntities() 

var student = ctx.Students.Where(s => s.Name == "John Doe").First();    

student.Name = "Erik Blessman";

ctx.SaveChanges(); // Will update the  student

Otherwise if this entity is manually created and does not belong to any DbContexts you will need to

  1. Attach your Entity to a new(or your current) DbContext (this will be automatically done for you if you set EntityState.Modified )
  2. Tell DbContext this entity has been modified by
    • var entry = context.Entry(entity); // Gets the entry for entity inside context
    • entry.State = EntryState.Modified; // Tell EF this entity has been modified
  3. Optionally tell EF which properties on your entity have been modified
  4. Call SaveChanges()
8
3/8/2015 10:57:34 PM

Popular Answer

http://www.entityframeworktutorial.net/EntityFramework4.3/update-entity-using-dbcontext.aspx

    Student stud;
    //1. Get student from DB
    using (var ctx = new SchoolDBEntities())
    {
        stud = ctx.Students.Where(s => s.StudentName == "New Student1").FirstOrDefault<Student>();
    }

    //2. change student name in disconnected mode (out of ctx scope)
    if (stud != null)
    {
        stud.StudentName = "Updated Student1";
    }

    //save modified entity using new Context
    using (var dbCtx = new SchoolDBEntities())
    {
        //3. Mark entity as modified
        dbCtx.Entry(stud).State = System.Data.Entity.EntityState.Modified;     

        //4. call SaveChanges
        dbCtx.SaveChanges();
    }


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow