EntityFramework 更新数据的几种方法
第一种:
先从数据库中取出数据,然后再更新字段。效率较低,需要2次数据库操作;
using (var db = new Entities()) { var data = db.Member.Find(5); data.Name = "new name"; db.SaveChanges(); }
生成的sql语句是:
select * from Member where ID=5 update Member set Name = 'new name' where ID=5
第二种:
根据主键更新某个字段。如下虽然定义的变量里有password,但是没有设置ismodified=true,所以在savechanges时只会更新name的值
using (var db = new Entities()) { var data = new Member() { ID = 5, Name = "aa", Password = "aa" }; db.Entry(data).State = EntityState.Unchanged;// 或db.Member.Attach(data); db.Entry<Member>(data).Property("Name").IsModified = true; db.SaveChanges(); }
生成的sql语句是:
update Member set Name='aa' where ID=5
第三种:
根据主键更新所有字段,如下虽然未定义password,但到数据库中会更新为null
using (var db = new ScratchDB2Entities()) { var data = new Member() { ID = 5, Name = "aa" }; db.Entry(data).State = EntityState.Modified; db.SaveChanges(); }
生成的sql语句是:
update Member set Name='aa',Password=null where ID=5