EF: Raw SQL Queries

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.

时间: 2024-10-11 01:39:37

EF: Raw SQL Queries的相关文章

Entity Framework Tutorial Basics(39):Raw SQL Query

Execute Native SQL Query You can execute native raw SQL query against the database using DBContext. You can execute the following types of queries: SQL query for entity types which returns particular types of entities SQL query for non-entity types w

EntityFramework Core Raw SQL

EntityFramework Core Raw SQL 基础查询(执行SQL和存储过程) 啥也不说了,拿起键盘就是干,如下:     public class HomeController : Controller     {        private IBlogRepository _blogRepository;        public HomeController(IBlogRepository blogRepository)         {             _blo

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

一:linq 对ef来说不是唯一性的query... 二:Entity Sql 1. esql => entity sql... [类sql的语言] 和sql差不多,但是呢,不是sql... using (SchoolDBEntities db = new SchoolDBEntities()) { //Querying with Object Services and Entity SQL string sqlString = "select Value s from SchoolDBE

关于EF输出sql的执行日志

sqlserver中可以使用sql profiler:但是mysql当中无法查看:只能借助于组件: ADO.NET Entity Framework CodeFirst 如何输出日志(EF4.3) 用的EFProviderWrappers ,这个组件好久没有更新了,对于SQL执行日志的解决方案的需求是杠杠的,今天给大家介绍一个更好的组件Clutch.Diagnostics.EntityFramework,可以通过Nuget 获取: 这个框架定义了一个接口 IDbTracingListener:

EF执行SQL语句和存储过程

EF虽然使用对象化的方式避免了我们写SQL,但是对于部分SQL,例如需要复杂的查询.执行插入和删除等可以操作,直接执行SQL可以减少减少性能上的损失. 使用EF执行SQL可以通过ExecuteSqlCommand()和SqlQuery()两个方法.这两个方法适用场景如下: ExecuteSqlCommand()不返回执行的结果,只返回受影响的行数,所以适用于数据库修改,数据创建,更新和删除等操作: SqlQuery()则会返回查询到的结果,并将结果保存在数据实体中: 使用ExecuteSqlCo

如何使用SQLAlchemy库写出防SQL注入的Raw SQL

Python阵营有很多操作数据库的开源库(安装pip后,可以借助"pip search mysql"查看可用的库列表),其中被使用最多的无疑是MySQLdb,这个库简单易上手.其偏底层的特性为开发者提供灵活性的同时,也对不少新手写出的DB操作代码提出了考验,因为它只支持raw sql,容易导致sql注入攻击. 鉴于此,很多库提供了ORM接口能力,借助OO思想,数据库中的表被映射为Python的类,类的对象代表数据表中的一行记录,所有的DB操作都通过对象方法调用来实现,这些调用在底层被自

Tracing SQL Queries in Real Time for MySQL Databases using WinDbg and Basic Assembler Knowledge

https://www.codeproject.com/Articles/43305/Tracing-SQL-Queries-in-Real-Time-for-MySQL-Databas Assembly and MySQL Introduction One of the more interesting things for any person is to see how the internal engines from the server software work. The purp

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 Queries in MySQL http://www.howtogeek.com/howto/database/monitor-all-sql-queries-in-mysql/ more: Using the New MySQL Query Profiler http://web.archive.org/w

设置 sqlserver Profiler 只监控 EF的sql执行请求

当我们用EF执行语句的时候,可以使用 sqlserver Profiler来监控到底执行了哪些sql语句,但是默认他是监控全局的,我们只想监控Ef的语句,这里如下设置 这样就只会监控 EF产生的 sql语句了 设置 sqlserver Profiler 只监控 EF的sql执行请求