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 DbSet object, 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 查询的更多相关文章

  1. django 视图中执行原生的 sql 查询语句

    可以使用objects的raw()方法执行原生的sql语句,进行对数据库的查询操作,raw()方法只能执行查询语句 query_set = your_model.objects.raw("s ...

  2. Jmeter执行多个sql查询语句

    1.添加jdbc connection(注意标红部分) 2.添加jdbc request 3.查看结果树 本文主要向大家介绍了Oracle数据库之jmeter jdbc request 如何运行多个s ...

  3. Django文档阅读之执行原始SQL查询

    Django提供了两种执行原始SQL查询的方法:可以使用Manager.raw()来执行原始查询并返回模型实例,或者可以完全避免模型层直接执行自定义SQL. 每次编写原始SQL时都要关注防止SQL注入 ...

  4. django 执行原始SQL

    二.知识点总结 When the model query APIs don’t go far enough, you can fall back to writing raw SQL. go far ...

  5. C# EF使用SqlQuery直接操作SQL查询语句或者执行过程

    Entity Framework是微软出品的高级ORM框架,大多数.NET开发者对这个ORM框架应该不会陌生.本文主要罗列在.NET(ASP.NET/WINFORM)应用程序开发中使用Entity F ...

  6. 在django中,执行原始sql语句

    extra()方法 结果集修改器,一种提供额外查询参数的机制 使用extra: 1:Book.objects.filter(publisher__name='广东人员出版社').extra(where ...

  7. .NET Entity Framework(EF)使用SqlQuery直接操作SQL查询语句或者执行过程

    Entity Framework是微软出品的高级ORM框架,大多数.NET开发者对这个ORM框架应该不会陌生.本文主要罗列在.NET(ASP.NET/WINFORM)应用程序开发中使用Entity F ...

  8. 一条查询SQL查询语句的执行原理

    先熟悉一下浅而易懂SQL执行的流程图SQL查询过程七步曲 1.查询SQL发送请求 客户端将查询sql按照mysql通信协议传输到服务端.服务端接受到请求后,服务端单起一个线程执行sql 2.判断是否为 ...

  9. Django当中的sql查询

    十二:在Django中使用sql   关键字: connection     connections       transaction insert/create/update/delete/sel ...

随机推荐

  1. (三)CSS高级语法

    选择器分组 可以对选择器进行分组,被分组的选择器可以分享相同的声明,用逗号将需要分组的选择器分开.例如: h1,h2,h3,h4,h5,h6 { color: green; } 继承以及其问题一般,子 ...

  2. JVM学习笔记(一)------基本结构

    从Java平台的逻辑结构上来看,我们可以从下图来了解JVM: 从上图能清晰看到Java平台包含的各个逻辑模块,也能了解到JDK与JRE的区别 对于JVM自身的物理结构,我们可以从下图鸟瞰一下: 对于J ...

  3. Pig简单入门

    pig是hadoop客户端,使用类似于SQL的面向数据流的语言pig latin,这个语言可以完成排序,过滤,求和,关联等操作,可以支持自定义函数.Pig自动把pig latin 映射为Map-Red ...

  4. apk反编译(3)smali语法

    from http://pallergabor.uw.hu/androidblog/dalvik_opcodes.html Dalvik opcodes Author: Gabor Paller Vx ...

  5. Android开发之网络请求HttpURLConnection

    转:http://blog.csdn.net/guolin_blog/article/details/12452307 Android中主要提供了两种方式来进行HTTP操作,HttpURLConnec ...

  6. tahoma字体对中文字的影响

    一提到tahoma字体大家都会想到,它是一个英文字体,对中文不会有影响. 但是今天就遇到一个问题,tahoma字体会影响中文字的显示,如: html代码: <div class="bo ...

  7. TCSRM 591 div2(1000)(dp)

    挺好的dp 因为有一点限制 必须任意去除一个数 总和就会小于另一个总和 换句话来说就是去除最小的满足 那么就都满足 所以是限制最小值的背包 刚开始从小到大定住最小值来背 TLE了一组数据 后来发现如果 ...

  8. UVa 10256 (判断两个凸包相离) The Great Divide

    题意: 给出n个红点,m个蓝点.问是否存在一条直线使得红点和蓝点分别分布在直线的两侧,这些点不能再直线上. 分析: 求出两种点的凸包,如果两个凸包相离的话,则存在这样一条直线. 判断凸包相离需要判断这 ...

  9. 试图从数据库 ‘UFData_001_2003' 中提取的逻辑页 (1:10720) 属于对象 '0',而非对象 'syscolumns'

    数据库可以使用,可以备份,但对备份进行恢复时报错,使用sp_attach_db对两个物理文件进行连接时,报同样错误: 服务器: 消息 605,级别 21,状态 1,行 1 试图从数据库 ‘UFData ...

  10. string.Format 里面包含 javascript方法参数的时候 单引号变成双引号的问题解决方法

    解决方法如下 StringBuilder sb = new StringBuilder(); var str =@"<label><input type='checkbox ...