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

时间:2013-05-30 05:58:57

标签: sql asp.net-mvc-3 entity-framework-5 edmx

我正在使用带有实体框架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查询?感谢。

2 个答案:

答案 0 :(得分:12)

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

  1. 返回特定类型实体的实体类型的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>();
      }
    
  2. 返回基本数据类型的非实体类型的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");
    
           }
    
  3. 数据库的原始SQL命令。

           onNext: function (tab, navigation, index) {
            if(index == 1) {
                if(form_header.valid() === true) {
    
                        $('#report_header_fm').submit(function(){
                        console.log('test123');
                        $.ajax({
                            type: "POST",
                            url: baseURL + "index.php/addNewReport",
                            data: $("#report_header_fm").serialize(),
                            success: function(data)
                            {
                                console.log('test');
                            }
    
                            });  //Ajax end
                    });
    
                    }
                else
                {
                     return false;
                }
                }
                handleTitle(tab, navigation, index);
    
                },
    
  4. 您也可以参考this

答案 1 :(得分:5)

这已经奏效!!

using (var ctx = new HR())
        {

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

            ctx.SaveChanges();
        }