gpt4 book ai didi

sql - 如何在 Entity Framework 中执行原始SQL查询?

转载 作者:行者123 更新时间:2023-12-04 13:16:51 26 4
gpt4 key购买 nike

我正在使用带有 Entity Framework 5的asp.net mvc3。我有.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查询?谢谢。

最佳答案

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

  • 用于查询实体类型的SQL查询,该查询返回特定类型的实体。
    using (var ctx = new SchoolDBEntities())
    {

    var studentList = ctx.Students.SqlQuery("Select * from Student").ToList<Student>();

    }
  • 用于非实体类型的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>();
    }
  • 到数据库的原始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

    关于sql - 如何在 Entity Framework 中执行原始SQL查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16828974/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com