2013-05-30 22 views
6

Tôi đang sử dụng asp.net mvc 3 với khung thực thể 5. Tôi có tệp .edmx của mình & có thể tương tác với cơ sở dữ liệu của tôi bằng linq hoặc SP, nhưng tôi muốn chạy một số câu lệnh sql thô. Tôi đang thử một cái gì đó như thế này:Làm cách nào để thực thi truy vấn sql thô trong khung thực thể?

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

là có thể thực hiện truy vấn sql theo cách này? Cảm ơn.

+0

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

+0

Bạn cũng có thể xem câu trả lời của tôi trên 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 –

Trả lời

10

Bạn có thể thực hiện các loại sau đây của các truy vấn:

  1. truy vấn SQL cho các loại thực thể mà trả về loại hình cụ thể của đơn vị.

    using (var ctx = new SchoolDBEntities()) 
    { 
    
        var studentList = ctx.Students.SqlQuery("Select * from Student").ToList<Student>(); 
    
    } 
    
  2. Truy vấn SQL cho các loại phi thực thể trả về kiểu dữ liệu nguyên thủy.

    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. Lệnh SQL thô vào cơ sở dữ liệu.

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

Bạn cũng có thể tham khảo this

5

Điều này đã hiệu quả !!

using (var ctx = new HR()) 
     { 

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

      ctx.SaveChanges(); 
     }