EF: Raw SQL Queries
Entity Framework allows you to query using LINQ with your entity classes. However, there may be times that you want to run queries using raw SQL directly against the database. This includes calling stored procedures, which can be helpful for Code First models that currently do not support mapping to stored procedures. The techniques shown in this topic apply equally to models created with Code First and the EF Designer.
Writing SQL queries for entities
The SqlQuery method on DbSet allows a raw SQL query to be written that will return entity instances. The returned objects will be tracked by the context just as they would be if they were returned by a LINQ query. For example:
using (var context = new BloggingContext())
{
var blogs = context.Blogs.SqlQuery("SELECT * FROM dbo.Blogs").ToList();
}
Note that, just as for LINQ queries, the query is not executed until the results are enumerated—in the example above this is done with the call to ToList.
Care should be taken whenever raw SQL queries are written for two reasons. First, the query should be written to ensure that it only returns entities that are really of the requested type. For example, when using features such as inheritance it is easy to write a query that will create entities that are of the wrong CLR type.
Second, some types of raw SQL query expose potential security risks, especially around SQL injection attacks. Make sure that you use parameters in your query in the correct way to guard against such attacks.
Loading entities from stored procedures
You can use DbSet.SqlQuery to load entities from the results of a stored procedure. For example, the following code calls the dbo.GetBlogs procedure in the database:
using (var context = new BloggingContext())
{
var blogs = context.Blogs.SqlQuery("dbo.GetBlogs").ToList();
}
You can also pass parameters to a stored procedure using the following syntax:
using (var context = new BloggingContext())
{
var blogId = 1;
var blogs = context.Blogs.SqlQuery("dbo.GetBlogById @p0", blogId).Single();
}
Writing SQL queries for non-entity types
A SQL query returning instances of any type, including primitive types, can be created using the SqlQuery method on the Database class. For example:
using (var context = new BloggingContext())
{
var blogNames = context.Database.SqlQuery<string>(
"SELECT Name FROM dbo.Blogs").ToList();
}
The results returned from SqlQuery on Database will never be tracked by the context even if the objects are instances of an entity type.
Sending raw commands to the database
Non-query commands can be sent to the database using the ExecuteSqlCommand method on Database. For example:
using (var context = new BloggingContext())
{
context.Database.SqlCommand(
"UPDATE dbo.Blogs SET Name = 'Another Name' WHERE BlogId = 1");
}
Note that any changes made to data in the database using ExecuteSqlCommand are opaque to the context until entities are loaded or reloaded from the database.
Output Parameters
If output parameters are used, their values will not be available until the results have been read completely. This is due to the underlying behavior of DbDataReader, see Retrieving Data Using a DataReader for more details.
EF: Raw SQL Queries的更多相关文章
- EF Core 2.1 Raw SQL Queries (转自MSDN)
Entity Framework Core allows you to drop down to raw SQL queries when working with a relational data ...
- Executing Raw SQL Queries using Entity Framework
原文 Executing Raw SQL Queries using Entity Framework While working with Entity Framework developers m ...
- Entity Framework Tutorial Basics(39):Raw SQL Query
Execute Native SQL Query You can execute native raw SQL query against the database using DBContext. ...
- EntityFramework Core Raw SQL
前言 本节我们来讲讲EF Core中的原始查询,目前在项目中对于简单的查询直接通过EF就可以解决,但是涉及到多表查询时为了一步到位就采用了原始查询的方式进行.下面我们一起来看看. EntityFram ...
- 了解entity framework其他query方式之Entity SQL,Raw Sql分析
一:linq 对ef来说不是唯一性的query... 二:Entity Sql 1. esql => entity sql... [类sql的语言] 和sql差不多,但是呢,不是sql... u ...
- 关于EF输出sql的执行日志
sqlserver中可以使用sql profiler:但是mysql当中无法查看:只能借助于组件: ADO.NET Entity Framework CodeFirst 如何输出日志(EF4.3) 用 ...
- Visual Studio Entity Framework (EF) 生成SQL 代码 性能查询
Visual Studio Entity Framework (EF) 生成SQL 代码 性能查询 SQL 中,有SQL Server Profiler可以用来查询性能以及查看外部调用的SQL ...
- Monitor All SQL Queries in MySQL (alias mysql profiler)
video from youtube: http://www.youtube.com/watch?v=79NWqv3aPRI one blog post: Monitor All SQL Querie ...
- Viewing the Raw SQL Statement(xcode で)
Thanks to Core Data. Even without learning SQL and database, you’re able to perform create, select, ...
随机推荐
- mysql-模拟全连接处理
方案:通过union连接查询出所有需要的特殊标签,然后在通过left join与union中的结果集做多表比较. sql select t.`code`,a.`count` as count_a,b. ...
- JS 打印功能代码可实现打印预览、打印设置等
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.or ...
- 【CodeForces 672B】Different is Good
题 字符串所有子串要不同.求修改最少多少个字符. 因为只能是26个字母,显然大于26的不可能有答案,其它情况ans+=u[i]-1:u[i]是字母出现的次数. #include<cstdio&g ...
- bbs树形打印(一)
前言:大家在bbs回帖时常常可以看到树形的回复形式. dfs设计 (1) 为使得Connection仅打开一次,因此以conn作为其中一个递归参数,在递归全程不关闭conn; (2)根据存入数据的树状 ...
- Numpy 用法小结
1. asarray 函数 可以将输入数据转化为矩阵格式. 输入数据可以是(列表,元组,列表的列表,元组的元组,元组的列表等这些数组形式). >>> asarray([(1,2,3 ...
- Hive 按某列的部分排序 以及 删列操作
脑袋果然还是智商不足. 涉及到的小需求: 某个表test 有一列 tc: a字符串+b字符串+c字符串 拼接组成 把test表,按b字符串排序 输出 遇到的问题: select 里面必须包含 orde ...
- BZOJ 1116: [POI2008]CLO
1116: [POI2008]CLO Time Limit: 10 Sec Memory Limit: 162 MBSubmit: 922 Solved: 514[Submit][Status][ ...
- css-transition和transform实现图片悬浮移动动画
今天在京东首页上看到一个效果,鼠标悬浮在图片上时,图片发生移动,鼠标移走时再移回,并且有一个过渡效果. 貌似很简单,自己做做试试吧 我首先使用的是jquery在鼠标悬浮到图片上给图片增加一个类,这个类 ...
- 【BZOJ-4435】Juice Junctions 最小割树(分治+最小割)+Hash
4435: [Cerc2015]Juice Junctions Time Limit: 20 Sec Memory Limit: 512 MBSubmit: 20 Solved: 11[Submi ...
- 【poj1160】 Post Office
http://poj.org/problem?id=1160 (题目链接) 题意 按照递增顺序给出一条直线上坐标互不相同的n个村庄,要求从中选择p个村庄建立邮局,每个村庄使用离它最近的那个邮局,使得所 ...