Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to edit object in Entity Framework?

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?

like image 807
FreeVice Avatar asked Apr 26 '26 05:04

FreeVice


1 Answers

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.

like image 173
dyslexicanaboko Avatar answered Apr 27 '26 17:04

dyslexicanaboko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!