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, ...
随机推荐
- 【USACO 1.3】Barn Repair
贪心,去掉最大的min(m,c)-1个间隔 /******************************************* TASK: barn1 LANG: C++ Created Tim ...
- Linux 查看文件内容
cat 由第一行开始显示档案内容 格式: cat [选项] [文件]... -A, --show-all 等价于 -vET -b, -- 对非空输出行编号 -e 等价于 -vE -E, --在每行 ...
- win7下php5.6安装redis扩展
redis扩展下载 http://windows.php.net/downloads/pecl/snaps/redis/ 查看phpinfo()信息 Compiler Architecture 选择合 ...
- iOS开发网络篇—监测网络状态(转)
文章转载自:http://www.cnblogs.com/wendingding/p/3950114.html iOS开发网络篇—监测网络状态 一.说明 在网络应用中,需要对用户设备的网络状态进行实时 ...
- css-关于absolute和relative的一些笔记
根据张鑫旭老师的博客,一些笔记留作备忘 1.position:absolute 具有包裹性--包裹性换种说法就是让元素inline-block化,例如一个div标签默认宽度是100%显示的,但是一旦被 ...
- linux永久更改eth0的ip地址
linux中永久修改ip和子网掩码,可以用命令也可以直接到文件里修改.这里推荐直接到文件中修改.1.进入网卡配置文件 vi /etc/sysconfig/network-scripts/ifcfg-e ...
- spring-HelloWorld
准备工作,安装SpringIDE,找到SpringSource-tool-suit,然后按照, 关键的一部在与找到之后该安转那些呢,答案是只安转带有SpringIDE的, 有四个,且不要点击联网进行更 ...
- 【poj2478】 Farey Sequence
http://poj.org/problem?id=2478 (题目链接) 题意 求分母小于等于n的真分数的个数. Solution 现在只能做做水题了,唉,思维僵化. 细节 前缀和开LL 代码 // ...
- 【poj3615】 Cow Hurdles
http://poj.org/problem?id=3615 (题目链接) 题意 给出一张有向图,求从u到v最大边最小的路径的最大边.→_→不会说话了.. Solution 好久没写Floyd了,水一 ...
- AppVeyor-CI为GitHub项目做自动化集成(dotnet为主)
travis-ci对dotnet的项目做自动化集成不太友好,尤其是使用mono的编译和不能使用MSTest进行自动化测试,所以转到appveyor进行. appveyor的配置非常简单,有两种方式: ...