Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update a row using Entity Framework code first?

How should I go about updating a row in the database? There is no update method, and if I use add and the primary key id already exists, I get an exception. Please provide an example if possible.

like image 935
Ryan Avatar asked Feb 08 '11 16:02

Ryan


2 Answers

The easiest way is:

(1) retrieve existing row using pk.

(2) update properties.

(3) call SaveChanges() on context.

e.g.

        var student = context.Students.Find(42);

        student.Description = "updated";

        context.SaveChanges();
like image 72
Paul Hiles Avatar answered Oct 22 '22 10:10

Paul Hiles


Here is a way that worked for me without having to make a query first:

context.Students.Attach(student);
context.Entry(student).State = EntityState.Modified;
context.SaveChanges();
like image 41
leojh Avatar answered Oct 22 '22 11:10

leojh