2013-05-30 17 views
6

Używam asp.net mvc 3 z encją framework 5. Mam plik .edmx & zdolny do interakcji z moją bazą danych za pomocą linq lub SP, ale chcę uruchomić jakieś surowe wyrażenie sql. Próbuję coś takiego:Jak wykonać surowe zapytanie sql w strukturze encji?

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

jest to możliwe, aby wykonać kwerendę sql w ten sposób? Dzięki.

+0

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

+0

Możesz również rzucić okiem na moją odpowiedź na 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 –

Odpowiedz

10

Można wykonać następujące rodzaje zapytań:

  1. zapytań SQL dla typów elementów, które zwraca poszczególnych rodzajów podmiotów.

    using (var ctx = new SchoolDBEntities()) 
    { 
    
        var studentList = ctx.Students.SqlQuery("Select * from Student").ToList<Student>(); 
    
    } 
    
  2. Zapytanie SQL dla typów innych niż encje, które zwracają pierwotny typ danych.

    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. Surowe polecenia SQL do bazy danych.

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

Można również zapoznać this

5

To zadziałało !!

using (var ctx = new HR()) 
     { 

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

      ctx.SaveChanges(); 
     } 
Powiązane problemy