2013-05-30 111 views
6

我正在使用實體框架5的asp.net mvc 3.我的.edmx文件&能夠使用linq或SP與我的數據庫交互,但我想運行一些原始的sql語句。我正在嘗試這樣的事情:如何在實體框架中執行原始sql查詢?

Using(var ctx=new HREntities()) 
{ 
    ctx.Database.ExecuteSqlCommand("insert into Employees values {0}, {1}", model.EMPLOYEEID, model.EMPLOYEENAME); 
    ctx.SaveChanges(); 
} 

是否有可能以這種方式執行sql查詢?謝謝。

+0

http://stackoverflow.com/questions/915329/is-it-possible-to-run-native-sql-with-entity-framework – Satpal

+0

你也可以看看我的答案http://stackoverflow.com/questions/16807334/execute-raw-sql-query-in-asp-net-mvc-database-first-mode/29147592#29147592 [1]:http://stackoverflow.com/questions/16807334/execute-raw-sql-query-in-asp-net-mvc-database-first-mode/29147592#29147592 –

回答

10

您可以執行查詢的以下幾種類型:

  1. 的實體類型的SQL查詢返回特定類型的實體。

    using (var ctx = new SchoolDBEntities()) 
    { 
    
        var studentList = ctx.Students.SqlQuery("Select * from Student").ToList<Student>(); 
    
    } 
    
  2. 針對返回原始數據類型的非實體類型的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>(); 
        } 
    
  3. 原始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

5

這已經奏效了!

using (var ctx = new HR()) 
     { 

      ctx.Database.ExecuteSqlCommand("insert into Employees values (9, 'Beverage')"); 

      ctx.SaveChanges(); 
     }