EntityFramework Core笔记:保存数据(4)
1. 基本保存
每个DBContext实例都有一个ChangeTracker,负责跟踪需要写入数据库的更改。当实例发生更改时,更改会被记录在ChangeTracker中,在调用 SaveChanges 时被写入数据库。
1.1 添加数据
使用 DbSet.Add()添加实体类的新实例。 调用 SaveChanges() 时,数据将插入到数据库中。
using (var context = new LibingContext())
{
var role = new Role
{
RoleName = "教师"
};
context.Roles.Add(role); context.SaveChanges();
}
1.2 更新数据
Entity Framwork Core将自动检测对由DbContext跟踪的实体所做的更改。
更新数据:修改属性值,调用 SaveChanges()。
using (var context = new LibingContext())
{
var role = context.Roles.Find();
role.RoleName = "教师"; context.SaveChanges();
}
1.3 删除数据
使用 DbSet.Remove() 删除实体类的实例。
如果实体已存在于数据库中,则 SaveChanges() 将删除该实体。 如果实体尚未保存到数据库(即跟踪为“已添加”),则 SaveChanges() 时,该实体会从上下文中删除且不再插入。
using (var context = new LibingContext())
{
var role = context.Roles.Find();
context.Roles.Remove(role); context.SaveChanges();
}
1.4 一个SaveChanges 中的多个操作
可以将多个添加/更新/删除操作合并到对“SaveChanges”的单个调用。
对于大多数数据库提供程序,“SaveChanges”是事务性的。
using (var context = new LibingContext())
{
// 新增
context.Roles.Add(new Role { RoleName = "管理员" });
context.Roles.Add(new Role { RoleName = "学生" }); // 修改
var modifyRole = context.Roles.Find();
modifyRole.RoleName = "教师"; // 删除
var deleteRole = context.Roles.Where(t => t.RoleID == ).FirstOrDefault();
context.Roles.Remove(deleteRole); context.SaveChanges();
}
2. 关联数据
2.1 添加新实体的关系图
using (var context = new LibingContext())
{
var category = new Category
{
CategoryName = "手机",
Products = new List<Product> {
new Product { ProductName = "华为", UnitPrice = },
new Product { ProductName = "小米", UnitPrice = }
}
};
context.Categories.Add(category); context.SaveChanges();
}
exec sp_executesql N'SET NOCOUNT ON;
INSERT INTO [Category] ([CategoryName])
VALUES (@p0);
SELECT [CategoryID]
FROM [Category]
WHERE @@ROWCOUNT = 1 AND [CategoryID] = scope_identity(); ',N'@p0 nvarchar(4000)',@p0=N'手机'
exec sp_executesql N'SET NOCOUNT ON;
INSERT INTO [Product] ([CategoryID], [ProductName], [UnitPrice])
VALUES (@p0, @p1, @p2);
SELECT [ProductID]
FROM [Product]
WHERE @@ROWCOUNT = 1 AND [ProductID] = scope_identity(); ',N'@p0 int,@p1 nvarchar(4000),@p2 decimal(4,0)',@p0=1,@p1=N'华为',@p2=2000
exec sp_executesql N'SET NOCOUNT ON;
INSERT INTO [Product] ([CategoryID], [ProductName], [UnitPrice])
VALUES (@p0, @p1, @p2);
SELECT [ProductID]
FROM [Product]
WHERE @@ROWCOUNT = 1 AND [ProductID] = scope_identity(); ',N'@p0 int,@p1 nvarchar(4000),@p2 decimal(4,0)',@p0=1,@p1=N'小米',@p2=1000
2.2 添加关联实体
如果从已由DbContext跟踪的实体的导航属性中引用新实体,则该实体将插入到数据库中。
using Microsoft.EntityFrameworkCore;
using (var context = new LibingContext())
{
var category = context.Categories
.Include(t => t.Products)
.Where(t => t.CategoryID == )
.FirstOrDefault();
category.Products.Add(new Product
{
ProductName = "VIVO",
UnitPrice =
}); context.SaveChanges();
}
SELECT TOP(1) [t].[CategoryID], [t].[CategoryName]
FROM [Category] AS [t]
WHERE [t].[CategoryID] = 1
ORDER BY [t].[CategoryID]
SELECT [t.Products].[ProductID], [t.Products].[CategoryID], [t.Products].[ProductName], [t.Products].[UnitPrice]
FROM [Product] AS [t.Products]
INNER JOIN (
SELECT TOP(1) [t0].[CategoryID]
FROM [Category] AS [t0]
WHERE [t0].[CategoryID] = 1
ORDER BY [t0].[CategoryID]
) AS [t1] ON [t.Products].[CategoryID] = [t1].[CategoryID]
ORDER BY [t1].[CategoryID]
exec sp_executesql N'SET NOCOUNT ON;
INSERT INTO [Product] ([CategoryID], [ProductName], [UnitPrice])
VALUES (@p0, @p1, @p2);
SELECT [ProductID]
FROM [Product]
WHERE @@ROWCOUNT = 1 AND [ProductID] = scope_identity(); ',N'@p0 int,@p1 nvarchar(4000),@p2 decimal(4,0)',@p0=1,@p1=N'VIVO',@p2=1500
2.3 更改关系
如果更改实体的导航属性,则将对数据库中的外键列进行相应的更改。
using (var context = new LibingContext())
{
var category = context.Categories.Find();
var product = context.Products.Find();
product.Category = category; context.SaveChanges();
}
exec sp_executesql N'SELECT TOP(1) [e].[CategoryID], [e].[CategoryName]
FROM [Category] AS [e]
WHERE [e].[CategoryID] = @__get_Item_0',N'@__get_Item_0 int',@__get_Item_0=2
exec sp_executesql N'SELECT TOP(1) [e].[ProductID], [e].[CategoryID], [e].[ProductName], [e].[UnitPrice]
FROM [Product] AS [e]
WHERE [e].[ProductID] = @__get_Item_0',N'@__get_Item_0 int',@__get_Item_0=1
exec sp_executesql N'SET NOCOUNT ON;
UPDATE [Product] SET [CategoryID] = @p0
WHERE [ProductID] = @p1;
SELECT @@ROWCOUNT; ',N'@p1 int,@p0 int',@p1=1,@p0=2
2.4 删除关系
可以通过将引用导航设置为 null 或从集合导航中删除相关实体来删除关系。
默认情况下,对于必选关系,将配置级联删除行为,并将从数据库中删除子实体/依赖实体。 对于可选关系,默认情况下不会配置级联删除,但会将外键属性设置为 null。
using (var context = new LibingContext())
{
var category = context.Categories
.Include(t => t.Products)
.Where(t => t.CategoryID == )
.FirstOrDefault(); //category.Products.Remove(category.Products.FirstOrDefault());
category.Products = null; context.SaveChanges();
}
SELECT TOP(1) [t].[CategoryID], [t].[CategoryName]
FROM [Category] AS [t]
WHERE [t].[CategoryID] = 1
ORDER BY [t].[CategoryID]
SELECT [t.Products].[ProductID], [t.Products].[CategoryID], [t.Products].[ProductName], [t.Products].[UnitPrice]
FROM [Product] AS [t.Products]
INNER JOIN (
SELECT TOP(1) [t0].[CategoryID]
FROM [Category] AS [t0]
WHERE [t0].[CategoryID] = 1
ORDER BY [t0].[CategoryID]
) AS [t1] ON [t.Products].[CategoryID] = [t1].[CategoryID]
ORDER BY [t1].[CategoryID]
exec sp_executesql N'SET NOCOUNT ON;
DELETE FROM [Product]
WHERE [ProductID] = @p0;
SELECT @@ROWCOUNT; ',N'@p0 int',@p0=2
exec sp_executesql N'SET NOCOUNT ON;
DELETE FROM [Product]
WHERE [ProductID] = @p0;
SELECT @@ROWCOUNT; ',N'@p0 int',@p0=3
3. 级联删除
EntityFramework Core笔记:保存数据(4)的更多相关文章
- EntityFramework Core笔记:查询数据(3)
1. 基本查询 1.1 加载全部数据 using System.Linq; using (var context = new LibingContext()) { var roles = contex ...
- 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 ...
- Android学习笔记——保存数据到SQL数据库中(Saving Data in SQL Databases)
知识点: 1.使用SQL Helper创建数据库 2.数据的增删查改(PRDU:Put.Read.Delete.Update) 背景知识: 上篇文章学习了保存文件,今天学习的是保存数据到SQL数据库中 ...
- Android学习笔记-保存数据的实现方法2-SharedPreferences
Android下,数据的保存,前面介绍过了,把数据保存到内存以及SD卡上,这次我们就介绍一下,更为常用的采用SharedPreferences的方式来保存数据, 1,得到SharedPreferenc ...
- Android学习笔记-保存数据的实现方法1
Android开发中,有时候我们需要对信息进行保存,那么今天就来介绍一下,保存文件到内存,以及SD卡的一些操作,及方法,供参考. 第一种,保存数据到内存中: //java开发中的保存数据的方式 pub ...
- 02-EF Core笔记之保存数据
EF Core通过ChangeTracker跟踪需要写入数据库的更改,当需要保存数据时,调用DbContext的SaveChanges方法完成保存. 基本的添加.更新.删除操作示例如下: using ...
- IdentityServer4 中文文档 -16- (快速入门)使用 EntityFramework Core 存储配置数据
IdentityServer4 中文文档 -16- (快速入门)使用 EntityFramework Core 存储配置数据 原文:http://docs.identityserver.io/en/r ...
- 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平台下, ...
随机推荐
- [翻译]Linux 内核里的数据结构 —— 基数树
目录 Linux 内核里的数据结构 -- 基数树 基数树 Radix tree Linux内核基数树API 链接 Linux 内核里的数据结构 -- 基数树 基数树 Radix tree 正如你所知道 ...
- unity transform 常用操作
1.寻找物体 1.1 寻找满足条件的子物体 ` public static Transform FindObj(Transform transform, Func<Transform, bool ...
- Spring MVC(一)五大核心组件和配置
一,五大核心组件 1.DispatcherServlet 请求入口 2.HandlerMapping 请求派发,负责请求和控制器建立一一对应的关系 3.Controller 处理器 4.Mod ...
- maven+springMVC(一)
[目录]
- 最新git源码下载地址
1.最新git源码下载地址: https://github.com/git/git/releases https://www.kernel.org/pub/software/scm/git/ 可以手动 ...
- git排除插件(.ignore)配置
# Created by .ignore support plugin (hsz.mobi) ### Maven template target/ ### JetBrains template # C ...
- CentOS 7 系统下 GitLab 搭建
参考地址:https://blog.csdn.net/t748588330/article/details/79915003 1. 安装:使用 GitLab 提供仓库在线安装 curl -sS htt ...
- MongoDB语法与现有关系型数据库SQL语法比较
MongoDB语法 MySql语法 db.test.find({'name':'foobar'}) <==> select ...
- ARTS打卡第三周
Algorithm 题目描述 Given an array of integers, find if the array contains any duplicates. Your function ...
- 在vultr安装和使用golang
1.vultr可以用微信或支付宝充值,方便.好像推荐别人用还能挣美分,懒得弄了,参加了一个充10刀送50刀的活动,感觉实惠(实际用时感觉有点小贵). 2.注册登录后,控制面板上billing可查看余额 ...