开发者

How to update a row using Entity Framework code first?

开发者 https://www.devze.com 2023-02-09 12:44 出处:网络
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开发者_开发百科ample if

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开发者_开发百科ample if possible.


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


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

精彩评论

暂无评论...
验证码 换一张
取 消