EF框架是微软推出的用于与数据库交互的组件,这里简单列出一些常用用法,代码来源于《EF6-DBFirst-Demo》。
向数据库增加、修改、删除一条新记录的写法
using (var context = new SchoolDBEntities()){//创建新实体学生var newStudent = context.Students.Add(new Student() {StudentName = "Jonathan", StudentAddress = new StudentAddress() {Address1 = "1, Harbourside", City = "Jersey City", State = "NJ" } });context.SaveChanges(); // 保存//修改newStudent.StudentName = "Alex";context.SaveChanges(); // 保存//删除context.Students.Remove(newStudent);context.SaveChanges(); // 保存}
插入或修改一个实体类
var newStudent = new Student() {StudentName = "Bill" };var existingStudent = new Student() {StudentID = 10, StudentName = "Chris" };using (var context = new SchoolDBEntities()){context.Entry(newStudent).State = newStudent.StudentID == 0 ? EntityState.Added : EntityState.Modified;context.Entry(existingStudent).State = existingStudent.StudentID == 0 ? EntityState.Added : EntityState.Modified;context.SaveChanges(); // 保存}
Linq语句的写法
using (var context = new SchoolDBEntities()){//返回名叫Bill的所有学生var students = (from s in context.Studentswhere s.StudentName == "Bill"select s).ToList();//统计同名var studentsWithSameName = context.Students.GroupBy(s => s.StudentName).Where(g => g.Count() > 1).Select(g => g.Key);Console.WriteLine("Students with same name");foreach (var stud in studentsWithSameName){Console.WriteLine(stud);}//按条件查记录var standard1Students = context.Students.Where(s => s.StandardId == 1).ToList();}
查找某实体
using (var context = new SchoolDBEntities()){var stud = context.Students.Find(1);Console.WriteLine(stud.StudentName + " found");}
执行SQL查询语句
using (var context = new SchoolDBEntities()){var studentList = context.Students.SqlQuery("Select * from Student").ToList<Student>();var student = context.Students.SqlQuery("Select StudentId, StudentName, StandardId, RowVersion from Student where StudentId = 1").ToList();}
执行SQL插入、修改、删除语句
using (var context = new SchoolDBEntities()){context.Database.Log = Console.Write;//Insert commandint noOfRowInsert = context.Database.ExecuteSqlCommand("insert into student(studentname) values('Robert')");//Update commandint noOfRowUpdate = context.Database.ExecuteSqlCommand("Update student set studentname ='Mark' where studentname = 'Robert'");//Delete commandint noOfRowDeleted = context.Database.ExecuteSqlCommand("delete from student where studentname = 'Mark'");}