如何在实体框架执行原始的SQL查询? [英] How to execute raw sql query with in entity framework?
问题描述
我使用asp.net MVC 3与实体框架5.我有我的.edmx文件和放大器;能够与使用LINQ或SP我的数据库交互,但我想运行一些原始的SQL语句。我想是这样的:
I'm using asp.net mvc 3 with entity framework 5. I have my .edmx file & able to interact with my database using linq or SP, but I want to run some raw sql statement. I'm trying something like this:
Using(var ctx=new HREntities())
{
ctx.Database.ExecuteSqlCommand("insert into Employees values {0}, {1}", model.EMPLOYEEID, model.EMPLOYEENAME);
ctx.SaveChanges();
}
,才有可能执行sql查询这种方式?谢谢你。
is it possible to execute sql query this way? Thanks.
推荐答案
您可以执行以下类型的查询:
You can execute the following types of queries:
-
对于实体类型的SQL查询返回特定类型的实体。
SQL query for entity types which returns particular types of entities.
using (var ctx = new SchoolDBEntities())
{
var studentList = ctx.Students.SqlQuery("Select * from Student").ToList<Student>();
}
对于非实体类型的SQL查询返回一个原始数据类型。
SQL query for non-entity types which returns a primitive data type.
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命令到数据库中。
Raw SQL commands to the database.
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");
}
您还可以参考<一个href=\"http://blogs.microsoft.co.il/gilf/2009/11/25/execute-t-sql-statements-in-entity-framework-4/\">this
这篇关于如何在实体框架执行原始的SQL查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!