asp.net MVC 增、删、改
增
public ActionResult Add(){TestDB6Entities db = new TestDB6Entities();var department = new Department(){Name = \"行政部门\",Remark = \"大家啊睡懒觉\"};db.Departments.Add(department); //第一种方法db.SaveChanges();db.Entry(department).State = System.Data.Entity.EntityState.Added; //第二种方法db.SaveChanges();//批量新增List<Department> departments = new List<Department>(){new Department(){Name = \"行政部门\",Remark = \"大家啊睡懒觉\"},new Department(){Name = \"哈哈哈哈\",Remark = \"大司马\"}};db.Departments.AddRange(departments);db.SaveChanges();return View();}
删
public ActionResult Delete(){TestDB6Entities db = new TestDB6Entities();//第一种var a = db.Departments.Find(2);db.Departments.Remove(a);db.SaveChanges();//第二种var de = new ClassInfo() {ID = 2};db.Entry(de).State = System.Data.Entity.EntityState.Deleted;db.SaveChanges();//批量删除 删除 Remark 字段 为空的字段List<Department> departments = db.Departments.Where(p => p.Remark == null).ToList();db.Departments.RemoveRange(departments);return View();}
改
public ActionResult Edit(){TestDB6Entities db = new TestDB6Entities();//第一种var dd = db.Departments.Find(1);dd.Remark = \"123\";//第二种var department = new Department(){ID=1,Name = \"行政部门\",Remark = \"dasd \"};db.Entry(department).State = System.Data.Entity.EntityState.Modified;return View();}