执行原始的 SQL 查询
The Entity Framework Code First API includes methods that enable you to pass SQL commands directly to the database. You have the following options:
- Use the DbSet.SqlQuery method for queries that return entity types. The returned objects must be of the type expected by the
DbSetobject, and they are automatically tracked by the database context unless you turn tracking off. (See the following section about the AsNoTracking method.) - Use the Database.SqlQuery method for queries that return types that aren't entities. The returned data isn't tracked by the database context, even if you use this method to retrieve entity types.
- Use the Database.ExecuteSqlCommand for non-query commands.
在 web 应用程序中执行 SQL 命令,您必须采取预防措施,以保护您的网站防止 SQL 注入攻击。一个办法就是使用参数化的查询,以确保提交的 web 页的字符串不能被解释为 SQL 命令。
==============================================================
调用一个查询,返回实体
string sql = "select * from users where uIsDel=@p0";
List<User> list = db.Users.SqlQuery(sql, "0").ToList();
exec sp_executesql N'select * from users where uIsDel=@p0',N'@p0 nvarchar(1)',@p0=N'0'
与如下语句相似
List<User> list = db.Users.Where(u => u.uIsDel == false).ToList();
SELECT
[Extent1].[uId] AS [uId],
[Extent1].[uName] AS [uName],
[Extent1].[uLoginName] AS [uLoginName],
[Extent1].[uPwd] AS [uPwd],
[Extent1].[uAddtime] AS [uAddtime],
[Extent1].[uIsDel] AS [uIsDel]
FROM [dbo].[Users] AS [Extent1]
WHERE 0 = [Extent1].[uIsDel]
==============================================================
调用一个查询,返回其他类型的对象
// Commenting out LINQ to show how to do the same thing in SQL.
//IQueryable<EnrollmentDateGroup> = from student in db.Students
// group student by student.EnrollmentDate into dateGroup
// select new EnrollmentDateGroup()
// {
// EnrollmentDate = dateGroup.Key,
// StudentCount = dateGroup.Count()
// };
//var data = db.Students.GroupBy(s => s.EnrollmentDate).Select(s => new EnrollmentDateGroup() { EnrollmentDate = s.Key, StudentCount = s.Count() });
// SQL version of the above LINQ code.
string query = "SELECT EnrollmentDate, COUNT(*) AS StudentCount "
+ "FROM Person "
+ "WHERE Discriminator = 'Student' "
+ "GROUP BY EnrollmentDate";
IEnumerable<EnrollmentDateGroup> data = db.Database.SqlQuery<EnrollmentDateGroup>(query);
复杂查询手写代码执行效率会更好。
============================================================
调用更新查询
ViewBag.RowsAffected= db.Database.ExecuteSqlCommand("UPDATE Course SET Credits = Credits * {0}", 2);
======================================================================================
不跟踪查询
Department duplicateDepartment = db.Departments
.Include("Administrator")
.Where(d => d.PersonID== department.PersonID)
.AsNoTracking()
.FirstOrDefault();
如果查询大量数据,且这些数据并不用于更新数据库,可以使用不跟踪查询。
如果从客户端绑定了实体类,并想直接用于更新,而之前因某些原因需要从数据库中读取相同主键记录到内存中进行处理,这时,读取记录应使用不跟踪查询,否则更新时会提示错误。
内存中的实体类是一个实体类的包装,里面包含许多用于维护数据的属性。
========================================================================================
查看 发送到数据库的SQL
publicActionResultIndex()
{
var courses = db.Courses;
var sql = courses.ToString();
returnView(courses.ToList());
}
publicActionResultIndex(int?SelectedDepartment)
{
var departments = db.Departments.OrderBy(q => q.Name).ToList();
ViewBag.SelectedDepartment=newSelectList(departments,"DepartmentID","Name",SelectedDepartment);
int departmentID =SelectedDepartment.GetValueOrDefault();
IQueryable<Course> courses = db.Courses
.Where(c =>!SelectedDepartment.HasValue|| c.DepartmentID== departmentID)
.OrderBy(d => d.CourseID)
.Include(d => d.Department);
var sql = courses.ToString();
returnView(courses.ToList());
}
sql变量就是要发送到数据库的sql语句。
====================================================================================
禁止创建代理 有时需要禁止实体框架创建代理实例。例如,人们通常认为序列化非代理实例要比序列化代理实例容易得多。可通过清除 ProxyCreationEnabled 标记来关闭代理创建功能。上下文的构造函数便是可执行此操作的一个位置。例如: public class BloggingContext : DbContext
{
public BloggingContext()
{
this.Configuration.ProxyCreationEnabled = false;
} public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
} 请注意,在无需代理执行任何操作的情况下,EF 不会为类型创建代理。这意味着,也可以通过使用封装和/或没有虚拟属性的类型,避免生成代理。
====================================================================================
关闭自动变化探测
Entity Framework Automatic Detect Changes When using most POCO entities the determination of how an entity has changed (and therefore which updates need to be sent to the database) is handled by the Detect Changes algorithm. Detect Changes works by detecting the differences between the current property values of the entity and the original property values that are stored in a snapshot when the entity was queried or attached. The techniques shown in this topic apply equally to models created with Code First and the EF Designer. By default, the Entity Framework performs Detect Changes automatically when the following methods are called:
DbSet.Find
DbSet.Local
DbSet.Remove
DbSet.Add
DbSet.Attach
DbContext.SaveChanges
DbContext.GetValidationErrors
DbContext.Entry
DbChangeTracker.Entries Disabling automatic detection of changes If you are tracking a lot of entities in your context and you call one of these methods many times in a loop, then you may get significant performance improvements by turning off detection of changes for the duration of the loop. For example: using (var context = new BloggingContext())
{
try
{
context.Configuration.AutoDetectChangesEnabled = false; // Make many calls in a loop
foreach (var blog in aLotOfBlogs)
{
context.Blogs.Add(blog);
}
}
finally
{
context.Configuration.AutoDetectChangesEnabled = true;
}
} Don’t forget to re-enable detection of changes after the loop — We've used a try/finally to ensure it is always re-enabled even if code in the loop throws an exception. An alternative to disabling and re-enabling is to leave automatic detection of changes turned off at all times and either call context.ChangeTracker.DetectChanges explicitly or use change tracking proxies diligently. Both of these options are advanced and can easily introduce subtle bugs into your application so use them with care.
==============================================================================
执行原始的 SQL 查询的更多相关文章
- django 视图中执行原生的 sql 查询语句
可以使用objects的raw()方法执行原生的sql语句,进行对数据库的查询操作,raw()方法只能执行查询语句 query_set = your_model.objects.raw("s ...
- Jmeter执行多个sql查询语句
1.添加jdbc connection(注意标红部分) 2.添加jdbc request 3.查看结果树 本文主要向大家介绍了Oracle数据库之jmeter jdbc request 如何运行多个s ...
- Django文档阅读之执行原始SQL查询
Django提供了两种执行原始SQL查询的方法:可以使用Manager.raw()来执行原始查询并返回模型实例,或者可以完全避免模型层直接执行自定义SQL. 每次编写原始SQL时都要关注防止SQL注入 ...
- django 执行原始SQL
二.知识点总结 When the model query APIs don’t go far enough, you can fall back to writing raw SQL. go far ...
- C# EF使用SqlQuery直接操作SQL查询语句或者执行过程
Entity Framework是微软出品的高级ORM框架,大多数.NET开发者对这个ORM框架应该不会陌生.本文主要罗列在.NET(ASP.NET/WINFORM)应用程序开发中使用Entity F ...
- 在django中,执行原始sql语句
extra()方法 结果集修改器,一种提供额外查询参数的机制 使用extra: 1:Book.objects.filter(publisher__name='广东人员出版社').extra(where ...
- .NET Entity Framework(EF)使用SqlQuery直接操作SQL查询语句或者执行过程
Entity Framework是微软出品的高级ORM框架,大多数.NET开发者对这个ORM框架应该不会陌生.本文主要罗列在.NET(ASP.NET/WINFORM)应用程序开发中使用Entity F ...
- 一条查询SQL查询语句的执行原理
先熟悉一下浅而易懂SQL执行的流程图SQL查询过程七步曲 1.查询SQL发送请求 客户端将查询sql按照mysql通信协议传输到服务端.服务端接受到请求后,服务端单起一个线程执行sql 2.判断是否为 ...
- Django当中的sql查询
十二:在Django中使用sql 关键字: connection connections transaction insert/create/update/delete/sel ...
随机推荐
- C# 调用命令行,参数有空格
在程序中调用cmd命令打开一个文件,而文件路径带有空格,如果直接把路径传给cmd,那么cmd就会把路径空格前面的部分当做是一个参数,空格后当做另一个参数,命令行执行把后边截掉了,导致程序出错,会弹出了 ...
- Java类型
Java类型 本地类型 描述boolean jboolean C/C++8位整型byte jbyte C/C++带符号的8位整型c ...
- C# Index 定义索---引具体使用
using System;using System.Collections.Generic;namespace TestThisIndex{ public class Program { ...
- Objective-C命名编写规范
There are only two hard things in Computer Science: cache invalidation and naming things. 在计算机科学中只有两 ...
- hibernate 中id生成策略
数据库的设计和操作中,我们通常会给表建立主键. 主键,可以分为自然主键和代理主键. 自然主键表示:采用具有业务逻辑含义的字段作为表的主键.比如在用户信息表中,采用用户的身份证号码作为主键.但是这样一来 ...
- Hibernate学习笔记之EHCache的配置
Hibernate默认二级缓存是不启动的,启动二级缓存(以EHCache为例)需要以下步骤: 1.添加相关的包: Ehcache.jar和commons-logging.jar,如果hibernate ...
- JSOI2015 分组赛记
分组赛结束了,虽然跟我关系不大,但是去了还是学到了不少东西 day1 上午报到,在宾馆遇到大神wzy,orz 好像没有参赛证发了,于是给我发了一个[工作证],233我是工作人员了,高贵冷艳 下午是常中 ...
- 自学了三天的SeaJs学习,解决了前端的一些问题,与小伙伴们一起分享一下!
我为什么学习SeaJs? [第一]:为了解决项目中资源文件版本号的问题,以及打包压缩合并等问题. [第二]:好奇心和求知欲.[我发现很多知名网站也都在使用(qq空间, msn, 淘宝等等),而且 Se ...
- 浏览器HTML5支持程度测试
/********************************************************************* * 浏览器HTML5支持程度测试 * 说明: * 想知道对 ...
- Java [leetcode 2] Add Two Numbers
问题描述: You are given two linked lists representing two non-negative numbers. The digits are stored in ...