How to edit object in Entity Framework?

12,053

Solution 1

see this article http://msdn.microsoft.com/en-us/library/bb738695.aspx and http://msdn.microsoft.com/en-us/library/bb386870.aspx sample about update with EF.
And this SO question about ApplyCurrentValues: ApplyCurrentValues in EF 4 to see how to work with AppliCurrentValues.

Solution 2

This is for .Net 4.0

For this example, lets assume we are dealing with Product objects.

using (DBEntities context = new DBEntities())
{
    //Must attach first and change the state to modified
    context.Products.Attach(product);

    //If you are using .Net 4.1 then you can use this line instead:
    //context.Entry(
    context.ObjectStateManager.ChangeObjectState(product, EntityState.Modified);

    context.SaveChanges();
}

If you are using .Net 4.1 then you can use "context.Entry(...)" instead of "context.ObjectStateManager.ChangeObjectState(product, EntityState.Modified)" as seen here: Example of context.Entry()

This is the most straight forward way to do it. It doesn't require that you pull the object from the DB first, you can just provide an object you were tinkering with. The only downside is that this updates all fields, not just a single field.

Share:
12,053
FreeVice
Author by

FreeVice

artifical intelligence, ERP, blockchain

Updated on June 28, 2022

Comments

  • FreeVice
    FreeVice almost 2 years

    DataContext.ApplyCurrentValues() needs entitySetName, what is it?

    I think that code would same:

        public void Edit(Products p)
        {
            DataContext.ApplyCurrentValues("Products", p);
            DataContext.SaveChanges();
        }
    

    Is it correct?