EntityFramework Core笔记:查询数据(3)
1. 基本查询
1.1 加载全部数据
using System.Linq;
using (var context = new LibingContext())
{
var roles = context.Roles.ToList();
}
1.2 加载单个实体
using (var context = new LibingContext())
{
var role = context.Roles.FirstOrDefault(t => t.RoleID == );
}
using (var context = new LibingContext())
{
var role = context.Roles.Find();
}
注:Find()根据主键值查询返回单个实体。
1.3 筛选条件
using (var context = new LibingContext())
{
var roles = context.Roles
.Where(t => t.RoleName == "管理员")
.ToList();
}
2. 加载关联数据
Entity Framework Core可以在实体模型中使用导航属性,来加载关联数据。
常见的3中关联数据加载方式:
(1)预先加载(Eager Loading):关联数据作为初始查询的一部分从数据库中加载
(2)显式加载(Explicit Loading):关联数据在后续用到时显式指定从数据中加载
(3)延迟加载(Lazy Loading):关联数据通过导航属性,以透明方式从数据库中加载
2.1 预先加载
使用Include()指定需要包含在查询结果中的关联数据。
using System.Linq;
using Microsoft.EntityFrameworkCore;
using (var context = new LibingContext())
{
var categories = context.Categories
.Include(t => t.Products)
.ToList();
}
2.2 显式加载
显式加载通过一个导航属性DbContext.Entry(...)API。
using (var context = new LibingContext())
{
var category = context.Categories.Find(); context.Entry(category)
.Collection(t => t.Products)
.Load(); category.Products.ForEach(product =>
{
Console.WriteLine("ProductID:{0},ProductName:{1}", product.ProductID, product.ProductName);
});
}
显式加载通过相关的实体的聚合运算符,而无需加载到内存的操作。
using (var context = new LibingContext())
{
var category = context.Categories.Find(); int count = context.Entry(category)
.Collection(t => t.Products)
.Query()
.Count();
}
筛选加载到内存的关联实体数据。
using (var context = new LibingContext())
{
var category = context.Categories.Find(); var products = context.Entry(category)
.Collection(t => t.Products)
.Query()
.Where(t => t.UnitPrice >= )
.ToList();
}
3. 跟踪与非跟踪
3.1 跟踪查询
Entity Framework Core跟踪状态的实体,在检测到改动的情况下,调用SaveChanges()时,将持久保存数据库中。
using (var context = new LibingContext())
{
var product = context.Products.Find();
product.UnitPrice = 100m; context.SaveChanges();
}
3.2 非跟踪查询
非跟踪查询在对查询数据只读情况下,可以加快执行。
using (var context = new LibingContext())
{
var products = context.Products
.AsNoTracking()
.ToList();
}
更改默认跟踪上下文实例级别的行为:
using (var context = new LibingContext())
{
context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; var products = context.Products
.ToList();
}
3.3 跟踪与投影
即使查询的结果类型不是实体类型,如果结果包含实体类型它们将仍在默认情况下跟踪。
在下面的查询,它返回匿名类型的实例Category集将跟踪结果中。
using (var context = new LibingContext())
{
var categories = context.Categories
.Select(t => new
{
Category = t,
Products = t.Products.Count()
});
}
如果结果集不包含任何实体类型,会不执行任何跟踪。
在下面的查询,这将返回一个匿名类型使用某些实体(但不实际实体类型的实例)中的值时,没有任何跟踪执行。
using (var context = new LibingContext())
{
var products = context.Products
.Select(t => new
{
ProductID = t.ProductID,
PrudctName = t.ProductName
});
}
4. 原始SQL查询
EntityFramework Core使用原始SQL查询限制条件:
(1)SQL查询返回字段必须属于实体类型
(2)SQL查询必须返回实体类型的所有属性
4.1 基本原始SQL查询
使用FromSql扩展方法,基于原始的 SQL 查询的 LINQ 查询。
using (var context = new LibingContext())
{
var products = context.Products
.FromSql("SELECT * FROM [dbo].[Product]")
.ToList();
}
使用原始的 SQL 查询来执行存储的过程。
CREATE PROCEDURE USP_GetProducts
AS
BEGIN
SELECT * FROM [dbo].[Product]
END
using (var context = new LibingContext())
{
var products = context.Products
.FromSql("EXECUTE [dbo].[USP_GetProducts]")
.ToList();
}
4.2 传递参数
SQL参数化可以防止收到SQL注入攻击。
CREATE PROCEDURE USP_GetProductsByUnitPrice
@UnitPrice DECIMAL(18, 2)
AS
BEGIN
SELECT * FROM [dbo].[Product]
WHERE [UnitPrice] >= @UnitPrice
END
using (var context = new LibingContext())
{
decimal unitprice = 100m;
var products = context.Products
.FromSql("EXECUTE [dbo].[USP_GetProducts] {0}", unitprice)
.ToList();
}
using System.Data;
using System.Data.SqlClient;
using (var context = new LibingContext())
{
var unitprice = new SqlParameter("@UnitPrice", SqlDbType.Decimal);
unitprice.Value = 100m; var products = context.Products
.FromSql("EXECUTE [dbo].[USP_GetProducts] @UnitPrice", unitprice)
.ToList();
}
5. 异步查询
异步操作使用场景:当等待一个比较耗时的操作时,使用异步来释放当前的托管线程而无需等待,不会阻塞当前线程的运行。
异步操作在主应用程序线程以外的线程中执行,应用程序可在异步方法执行其任务时继续执行。
异步查询在数据库中执行查询时可以避免阻止线程。
Entity Framework Core提供的异步查询扩展方法包括:ToListAsync(),ToArrayAsync(),SingleAsync()等。
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
public async Task<List<Product>> GetProductsAsync()
{
using (var context = new LibingContext())
{
return await context.Products.ToListAsync();
}
}
EntityFramework Core笔记:查询数据(3)的更多相关文章
- EntityFramework Core笔记:表结构及数据基本操作(2)
1. 表结构操作 1.1 表名 Data Annotations: using System.ComponentModel.DataAnnotations.Schema; [Table("R ...
- EntityFramework Core笔记:入门(1)
1. 安装运行环境 EntityFramework Core运行环境,安装NuGget包: //Sql Server Database Provider PM> Install-Package ...
- EntityFramework Core笔记:保存数据(4)
1. 基本保存 每个DBContext实例都有一个ChangeTracker,负责跟踪需要写入数据库的更改.当实例发生更改时,更改会被记录在ChangeTracker中,在调用 SaveChanges ...
- EntityFramework Core数据查询
前言 本节我们再来讲讲EF Core,本节算是回归基础吧,当前项目EF Core还是处于1.1版本中,后续等待.net core等版本稳定了全部会更新到2.0版本中,到时再来更新相关文章分享给大家. ...
- 03-EF Core笔记之查询数据
EF Core使用Linq进行数据查询. 基本查询 微软提供了一百多个示例来演示查询,地址:https://code.msdn.microsoft.com/101-LINQ-Samples-3fb98 ...
- EntityFramework Core查询问题集锦(一)
前言 和大家脱离了一段时间,有时候总想着时间挤挤总是会有的,但是并非人愿,后面会借助周末的时间来打理博客,如有问题可以在周末私信我或者加我QQ皆可,欢迎和大家一起探讨,本节我们来讨论EF Core中的 ...
- EntityFramework Core 2.0执行原始查询如何防止SQL注入?
前言 接下来一段时间我们来讲讲EntityFramework Core基础,精简的内容,深入浅出,希望为想学习EntityFramework Core的童鞋提供一点帮助. EntityFramewor ...
- EntityFramework Core 2.0 Explicitly Compiled Query(显式编译查询)
前言 EntityFramework Core 2.0引入了显式编译查询,在查询数据时预先编译好LINQ查询便于在请求数据时能够立即响应.显式编译查询提供了高可用场景,通过使用显式编译的查询可以提高查 ...
- Webservice WCF WebApi 前端数据可视化 前端数据可视化 C# asp.net PhoneGap html5 C# Where 网站分布式开发简介 EntityFramework Core依赖注入上下文方式不同造成内存泄漏了解一下? SQL Server之深入理解STUFF 你必须知道的EntityFramework 6.x和EntityFramework Cor
Webservice WCF WebApi 注明:改编加组合 在.net平台下,有大量的技术让你创建一个HTTP服务,像Web Service,WCF,现在又出了Web API.在.net平台下, ...
随机推荐
- Java开发笔记(十七)各得其所的多路分支
前面提到条件语句的标准格式为“if (条件) { /* 条件成立时的操作代码 */ } else { /* 条件不成立时的操作代码 */ }”,乍看之下仿佛只有两个分支,一个是条件成立时的分支,另一个 ...
- springmvc 文件上传(粘贴即用)
这里记录下,方便以后复制粘贴. maven配置 <dependency> <groupId>commons-fileupload</groupId> <art ...
- WEB前端 HTML
目录 WEB前端 HTML WEB前端 HTML TOC 什么是html? html的固有结构 注释 什么是标签? 标签分类 什么是标签属性? 适用于大多数HTML标签的属性 常用标签 常用引用标签 ...
- Python re 模块
Python re 模块 TOC 介绍 作用 正则表达式语法 贪婪和非贪婪 普通字符和特殊字符 分组(比较重要) re modul level 方法 正则表达式对象 匹配对象 常用例子 注意事项 Ja ...
- django项目环境搭建
本文转载自: https://blog.csdn.net/xiaogeldx/article/details/89038299 在码云平台创建项目 版本控制的种类 主要使用github(最主流) 国内 ...
- Windows Server 2012 NIC Teaming 网卡绑定介绍及注意事项
Windows Server 2012 NIC Teaming 网卡绑定介绍及注意事项 转载自:http://www.it165.net/os/html/201303/4799.html Window ...
- Lcd(一)显示原理
一.LCD控制原理 S5PV210处理器中自带LCD控制器,控制LCD的显示,把 LCD 图像数据从一个位于系统内存的 video buffer 传送到一个外部的 LCD 驱动器接口. 类型: STN ...
- LSB和MSB
最低有效位(the least significant bit,lsb)是指一个二进制数字中的第0位(即最低位),具有权值为2^0,可以用它来检测数的奇偶性.与之相反的称之为最高有效位.在大端序中,l ...
- iOS中Realm数据库的基本用法
原文 http://git.devzeng.com/blog/simple-usage-of-realm-in-ios.html 主题 RealmiOS开发 Realm是由 Y Combinat ...
- redhat yum ISO 本地源
先将ISO文件挂载起来: [root@racdb1 ~]# mount -o loop /opt/soft/rhel-server-6.8-x86_64-dvd.iso /mnt/iso [root@ ...