EF实体类的增删改查操作

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/voodooer/article/details/52220417
            //新增
            //传统写法
            Entities es = new Entities();
            Sys_student stu = new Sys_student() {  Name = "测试" };
            es.Sys_student.Add(stu);
            es.SaveChanges();

            //通过属性来实现

            Sys_student stu = new Sys_student() { Name = "测试" };
            DbEntityEntry<Sys_student> entry = es.Entry<Sys_student>(stu);
            entry.State = System.Data.Entity.EntityState.Added;
            es.SaveChanges();


            //修改
            Entities es = new Entities();
            Sys_student stu = new Sys_student() { ID = 41, Name = "测试" };
            DbEntityEntry<Sys_student> entry = es.Entry<Sys_student>(stu);
            entry.State = System.Data.Entity.EntityState.Unchanged;
            entry.Property("Name").IsModified = true;
            es.SaveChanges();
            Console.WriteLine("修改数据成功!");
 
//删除
//传统写法
int id = 1001;
Sys_student stu = es.Sys_students.Find(id);
es.Sys_students.Remove(stu);
es.SaveChanges();
//不查找数据,直接删除
Sys_student stu = new Sys_student{ID=1001};
es.Sys_students.Attach(stu);
es.Sys_students.Remove(stu);
es.SaveChanges();
阅读更多

没有更多推荐了,返回首页