EF 增删改
一、新增
UserInfo user = new UserInfo() { UserName = "jamsebing", UserPass = "123456" }; db.UserInfo.Add(user);
二、删除之 [Entry].State=Deleted
var user = new UserInfo() { UserID = 1, //根据主键删除 UserName="jamesbing" }; db.Entry<UserInfo>(user).State = System.Data.Entity.EntityState.Deleted;
这里指定了UserName没有任何意义,只需填写UserId即可
删除之 [Attach+Remove]
var user = new UserInfo() { UserID = 1 //根据主键删除 }; //Attach的实体事先不能已经在内存中,否则上下文会追踪到两个相同键名的实体 //将对象添加到EF管理容器中 ObjectStateManager db.UserInfo.Attach(user); ////将对象包装类状态标识为删除 db.UserInfo.Remove(user);
删除之 [先查询实体 再删除]
// 执行了2次sql 效率略低 ,一次查询,一次删除 var user = (from u in db.UserInfo where u.UserID == 1 select u).FirstOrDefault(); db.UserInfo.Remove(user); db.SaveChanges();
三、修改整个实体 [Entry].State=Modified
//手动创建整个修改实体 var user = new UserInfo() { UserID = 1, UserName = "jamesbing2", UserPass = "654321" }; db.Entry<UserInfo>(user).State = System.Data.Entity.EntityState.Modified;
修改指定字段之 [Attach(entity)]
var user = new UserInfo() { UserID = 1, UserName = "jamesbing2" };
//State默认值=System.Data.EntityState.Unchanged
var entry=db.UserInfo.Attach(user);
//设置需要修改的字段
entry.Property<string>(v => v.UserName).IsModified = true;
修改指定字段之 [Entry(entity)].State=Unchanged
var user = new UserInfo() { UserID = 1, UserName = "jamesbing2" }; var entry= db.Entry<UserInfo>(user);
//如果使用 Attach 就不需要这句 entry.State = System.Data.EntityState.Unchanged;
//设置需要修改的字段 entry.Property<string>(v => v.UserName).IsModified = true;