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的更多相关文章

  1. 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 ...

  2. Executing Raw SQL Queries using Entity Framework

    原文 Executing Raw SQL Queries using Entity Framework While working with Entity Framework developers m ...

  3. Entity Framework Tutorial Basics(39):Raw SQL Query

    Execute Native SQL Query You can execute native raw SQL query against the database using DBContext. ...

  4. EntityFramework Core Raw SQL

    前言 本节我们来讲讲EF Core中的原始查询,目前在项目中对于简单的查询直接通过EF就可以解决,但是涉及到多表查询时为了一步到位就采用了原始查询的方式进行.下面我们一起来看看. EntityFram ...

  5. 了解entity framework其他query方式之Entity SQL,Raw Sql分析

    一:linq 对ef来说不是唯一性的query... 二:Entity Sql 1. esql => entity sql... [类sql的语言] 和sql差不多,但是呢,不是sql... u ...

  6. 关于EF输出sql的执行日志

    sqlserver中可以使用sql profiler:但是mysql当中无法查看:只能借助于组件: ADO.NET Entity Framework CodeFirst 如何输出日志(EF4.3) 用 ...

  7. Visual Studio Entity Framework (EF) 生成SQL 代码 性能查询

    Visual Studio Entity Framework (EF) 生成SQL 代码 性能查询     SQL 中,有SQL Server Profiler可以用来查询性能以及查看外部调用的SQL ...

  8. 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 ...

  9. Viewing the Raw SQL Statement(xcode で)

    Thanks to Core Data. Even without learning SQL and database, you’re able to perform create, select, ...

随机推荐

  1. spring第一课,beans配置(上)

    1.通过property配置bean <!-- 配置一个 bean --> <bean id="helloWorld" class="com.atgui ...

  2. jquery datatable(二)

    <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> ...

  3. 【转】Private Libraries、Referenced Libraries、Dependency Libraries的区别

    一.v4.v7.v13的作用和用法 1.Android Support V4, V7, V13是什么? 本质上就是三个java library. 2.为什么要有support库?   是为了解决软件的 ...

  4. 【bzoj2654】 tree

    http://www.lydsy.com/JudgeOnline/problem.php?id=2654 (题目链接) 题意 给你一个无向带权连通图,每条边是黑色或白色.让你求一棵最小权的恰好有nee ...

  5. BZOJ3240 [Noi2013]矩阵游戏

    本文版权归ljh2000和博客园共有,欢迎转载,但须保留此声明,并给出原文链接,谢谢合作. 本文作者:ljh2000作者博客:http://www.cnblogs.com/ljh2000-jump/转 ...

  6. VS提示“项目文件" "已被重命名或已不在解决方案中”的解决办法 .

    多个项目的源码在一个源代码中,其中,有一个源代码废弃不可用了.删除后,再次生成解决方案时出现了问题“项目文件" "已被重命名或已不在解决方案中”. 解决方法是: 1.找到主项目,右 ...

  7. poj 2945 trie树统计字符串出现次数

    用记录附加信息的val数组记录次数即可. trie的原理:每个可能出现的字目给一个编号c,那么整个树就是一个c叉树 ch[u][c]表示 节点u走c边过去之后的节点 PS:trie树还有种动态写法,使 ...

  8. Bzoj2434 [Noi2011]阿狸的打字机

    Time Limit: 10 Sec  Memory Limit: 256 MBSubmit: 2536  Solved: 1415 Description 阿狸喜欢收藏各种稀奇古怪的东西,最近他淘到 ...

  9. dbm速算

    经常用到,但是经常搞忘记.在这里记录一下换算的一些技巧. 为什么要用dB 在最前面,需要解释一下dB的由来,这样会让理解变得简单一点.事实上,dB(分贝)是一个纯计数单位.使用dB的目的呢,其实就是用 ...

  10. Python的设计哲学探究

    在Python shell中输入import this就会在屏幕上打印出来Python的设计哲学,如下: In [25]: import this The Zen of Python, by Tim ...