How to update a row using Entity Framework code first?

我的未来我决定 提交于 2019-12-21 04:06:36

问题


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:


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



回答2:


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


来源:https://stackoverflow.com/questions/4935371/how-to-update-a-row-using-entity-framework-code-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!