9

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
  • Identify the database in question. Commented Feb 8, 2011 at 16:08

2 Answers 2

21

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(); 
Sign up to request clarification or add additional context in comments.

1 Comment

This is easiest way, but it makes one more query to the database doesn't it? I mean it must do the SELECT to find the entity you wanna update and then update it. But in general you should be able to do it without this query just with UPDATE. Is there such way?
19

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.