In Entity Framework, how do you change an object?

ado.net c# entity-framework

Question

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?

1
3
2/16/2011 9:13:21 AM

Accepted Answer

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.

0
5/23/2017 12:06:32 PM

Popular Answer

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.



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