BreakHead
BreakHead

Reputation: 10672

How to update an object using Entity Framework

I am able to add data, but not sure how should I update the data. I am getting AddObject,DeleteObject methods not found any method to update.

Thanks

Upvotes: 2

Views: 7992

Answers (2)

Femaref
Femaref

Reputation: 61437

You simply grab an (or multiple) object(s), manipulate them and call SaveChanges on the context. Of course, the object has to be attached to the context and tracking must enabled.

var obj = context.table.First(o => o.ID == 1);
obj.Property1 = data;
context.SaveChanges();

Upvotes: 5

Ashraf Alam
Ashraf Alam

Reputation: 3650

Taken from Employee Info Starter Kit, you can consider the code snippet as below:

public void UpdateEmployee(Employee updatedEmployee)
        {
            //attaching and making ready for parsistance
            if (updatedEmployee.EntityState == EntityState.Detached)
                _DatabaseContext.Employees.Attach(updatedEmployee);
            _DatabaseContext.ObjectStateManager.ChangeObjectState(updatedEmployee, System.Data.EntityState.Modified);
            _DatabaseContext.SaveChanges();
        }

Upvotes: 5

Related Questions