欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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;//全字段更新
相关标签: C# 知识点