EF 增删改查的内存状态详解
程序员文章站
2022-07-13 22:40:35
...
User userNew = new User()
{
Account = "Admin",
State = 0,
CompanyId = 4,
CompanyName = "天国集团",
CreateTime = DateTime.Now,
CreatorId = 1,
Email = "[email protected]",
LastLoginTime = null,
LastModifierId = 0,
LastModifyTime = DateTime.Now,
Mobile = "13960699696",
Name = "yoyo",
Password = "12356789",
UserType = 1
};
using (JDDbContext context = new JDDbContext())
{
Console.WriteLine(context.Entry<User>(userNew).State);//实体跟context没关系 Detached
userNew.Name = "小鱼";
context.SaveChanges();//Detached啥事儿不发生
context.Users.Add(userNew);
Console.WriteLine(context.Entry<User>(userNew).State);//Added
context.SaveChanges();//插入数据(自增主键在插入成功后,会自动赋值过去)
Console.WriteLine(context.Entry<User>(userNew).State);//Unchanged(跟踪,但是没变化)
userNew.Name = "加菲猫";//修改----内存clone
Console.WriteLine(context.Entry<User>(userNew).State);//Modified
context.SaveChanges();//更新数据库,因为状态是Modified
Console.WriteLine(context.Entry<User>(userNew).State);//Unchanged(跟踪,但是没变化)
context.Users.Remove(userNew);
Console.WriteLine(context.Entry<User>(userNew).State);//Deleted
context.SaveChanges();//删除数据,因为状态是Deleted
Console.WriteLine(context.Entry<User>(userNew).State);//Detached已经从内存移除了
//user.Name = "IT小白龙";//只能更新这个字段
//context.Entry<User>(user).State = EntityState.Modified;//全字段更新
上一篇: kubernetes etcd备份与恢复
下一篇: c# 数据结构与算法解读篇(数组的使用)
推荐阅读