如何在实体框架中执行原始sql查询?

前端之家收集整理的这篇文章主要介绍了如何在实体框架中执行原始sql查询?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用带有实体框架5的asp.net mvc 3.我有我的.edmx文件&能够使用 linq或SP与我的数据库进行交互,但我想运行一些原始的sql语句.我正在尝试这样的事情:
Using(var ctx=new HREntities())
{
  ctx.Database.ExecutesqlCommand("insert into Employees values {0},{1}",model.EMPLOYEEID,model.EMPLOYEENAME);
  ctx.SaveChanges();
}

是否有可能以这种方式执行SQL查询?谢谢.

解决方法

您可以执行以下类型的查询

>返回特定类型实体的实体类型的SQL查询.

using (var ctx = new SchoolDBEntities())
 {

     var studentList = ctx.Students.sqlQuery("Select * from Student").ToList<Student>();

}

>返回基本数据类型的非实体类型的SQL查询.

using (var ctx = new  SchoolDBEntities())
{

var studentName = ctx.Students.sqlQuery("Select studentid,studentname 
    from Student where studentname='New Student1'").ToList();
}


 //Error
 using (var ctx = new SchoolDBEntities())
 {                
     //this will throw an exception
     var studentName = ctx.Students.sqlQuery("Select studentid as id,studentname as name 
        from Student where studentname='New Student1'").ToList();
 }

 //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>();
  }

>对数据库的原始sql命令.

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");

       }

你也可以参考this

原文链接:https://www.f2er.com/mssql/76399.html

猜你在找的MsSQL相关文章