Пример #1
0
        static void DeleteStudents()
        {
            //根据主键构建一个对象
            Students student = new Students
            {
                StudentId = 100000
            };

            //第一种写法:通过设置状态
            using (StudentManageDBEntities db = new StudentManageDBEntities())
            {
                db.Set <Students>().Attach(student);
                db.Entry(student).State = EntityState.Deleted;
                db.SaveChanges();
            }

            //第二种写法:通过remove方法
            using (StudentManageDBEntities db = new StudentManageDBEntities())
            {
                db.Set <Students>().Attach(student);
                db.Students.Remove(student);
                db.SaveChanges();//跟新到数据库(自动生成SQL语句)
            }

            //第三种写法:先查寻,再删除

            using (StudentManageDBEntities db = new StudentManageDBEntities())
            {
                var stu = db.Students.Where(o => o.StudentId == 100000).FirstOrDefault();
                db.Students.Remove(stu);
                db.SaveChanges();//跟新到数据库(自动生成SQL语句)
            }
        }
Пример #2
0
        static void Delete2()
        {
            StudentManageDBEntities db = new StudentManageDBEntities();
            Students student           = new Students
            {
                StudentId = 100013,
            };

            db.Set <Students>().Attach(student);
            db.Entry(student).State = EntityState.Deleted;

            //提交
            int result = db.SaveChanges();//跟新到数据库(自动生成SQL语句)

            Console.WriteLine("影响行数:" + result);
        }