How to update a row using Entity Framework code fi

2019-03-26 00:13发布

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.

2条回答
趁早两清
2楼-- · 2019-03-26 00:47

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();
查看更多
姐就是有狂的资本
3楼-- · 2019-03-26 00:56

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();
查看更多
登录 后发表回答