How can I use Entity Framework code to update a row first?

code-first entity-framework

Question

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.

1
9
8/23/2014 9:11:30 PM

Accepted Answer

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();
21
2/8/2011 4:11:29 PM

Popular Answer

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();


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