How to update a row using Entity Framework code first?

后端 未结 2 2060
不思量自难忘°
不思量自难忘° 2021-02-14 22:29

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 ex

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-14 22:55

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

提交回复
热议问题