SQL query for entity types:
using (var ctx = new SchoolDBEntities()) { var studentList = ctx.Students.SqlQuery("Select * from Student").ToList<Student>(); }
注意:查询的字段必须和实体中的属性名对应
SQL query for non-entity types:
using (var ctx = new SchoolDBEntities()) { //Get student name of string type string studentName = ctx.Database.SqlQuery<string>("Select studentname from Student where studentid=1").FirstOrDefault<string>(); }
Raw SQL commands to the database:
using (var ctx = new SchoolDBEntities()) { //Update command int noOfRowUpdated = ctx.Database.ExecuteSqlCommand("Update student set studentname ='changed student by command' where studentid=1"); //Insert command int noOfRowInserted = ctx.Database.ExecuteSqlCommand("insert into student(studentname) values('New Student')"); //Delete command int noOfRowDeleted = ctx.Database.ExecuteSqlCommand("delete from student where studentid=1"); }