6

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

4

2 回答 2

12

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

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

你也可以参考这个

于 2015-07-03T05:36:22.183 回答
5

这已经奏效了!!

using (var ctx = new HR())
        {

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

            ctx.SaveChanges();
        }
于 2013-06-03T09:15:41.420 回答