網站首頁 編程語言 正文
1.簡介
每個上下文實例都有一個ChangeTracker,它負責跟蹤需要寫入數據庫的更改。更改實體類的實例時,這些更改會記錄在ChangeTracker中,然后在調用SaveChanges時會被寫入數據庫中。此數據庫提供程序負責將更改轉換為特定于數據庫的操作(例如,關系數據庫的INSERT、UPDATE和DELETE命令)。
2.基本保存
了解如何使用上下文和實體類添加、修改和刪除數據。
2.1添加數據
使用DbSet.Add方法添加實體類的新實例。調用SaveChanges時,數據將插入到數據庫中。
using (var context = new BloggingContext()) { var blog = new Blog { Url = "http://sample.com" }; context.Blogs.Add(blog); context.SaveChanges(); }
2.2更新數據
EF將自動檢測對由上下文跟蹤的現有實體所做的更改。這包括從數據庫加載查詢的實體,以及之前添加并保存到數據庫的實體。只需通過賦值來修改屬性,然后調用SaveChanges即可。
using (var context = new BloggingContext()) { var blog = context.Blogs.First(); blog.Url = "http://sample.com/blog"; context.SaveChanges(); }
2.3刪除數據
使用DbSet.Remove方法刪除實體類的實例。如果實體已存在于數據庫中,則將在SaveChanges期間刪除該實體。如果實體尚未保存到數據庫(即跟蹤為“已添加”),則在調用SaveChanges時,該實體會從上下文中移除且不再插入。
using (var context = new BloggingContext()) { var blog = context.Blogs.First(); context.Blogs.Remove(blog); context.SaveChanges(); }
2.4單個SaveChanges中的多個操作
可以將多個添加/更新/刪除操作合并到對SaveChanges的單個調用。
using (var context = new BloggingContext()) { // add context.Blogs.Add(new Blog { Url = "http://sample.com/blog_one" }); context.Blogs.Add(new Blog { Url = "http://sample.com/blog_two" }); // update var firstBlog = context.Blogs.First(); firstBlog.Url = ""; // remove var lastBlog = context.Blogs.Last(); context.Blogs.Remove(lastBlog); context.SaveChanges(); }
3.保存關聯數據
除了獨立實體以外,還可以使用模型中定義的關系。
3.1添加關聯數據
如果創建多個新的相關實體,則將其中一個添加到上下文時也會添加其他實體。在下面的示例中,博客和三個相關文章會全部插入到數據庫中。找到并添加這些文章,因為它們可以通過Blog.Posts導航屬性訪問。
using (var context = new BloggingContext()) { var blog = new Blog { Url = "http://blogs.msdn.com/dotnet", Posts = new List{ new Post { Title = "Intro to C#" }, new Post { Title = "Intro to VB.NET" }, new Post { Title = "Intro to F#" } } }; context.Blogs.Add(blog); context.SaveChanges(); }
3.2添加相關實體
如果從已由上下文跟蹤的實體的導航屬性中引用新實體,則將發現該實體并將其插入到數據庫中。在下面的示例中,插入post實體,因為該實體會添加到已從數據庫中提取的blog實體的Posts屬性。
using (var context = new BloggingContext()) { var blog = context.Blogs.Include(b => b.Posts).First(); var post = new Post { Title = "Intro to EF Core" }; blog.Posts.Add(post); context.SaveChanges(); }
3.3更改關系
如果更改實體的導航屬性,則將對數據庫中的外鍵列進行相應的更改。在下面的示例中,post實體更新為屬于新的blog實體,因為其Blog導航屬性設置為指向blog,blog也會插入到數據庫中,因為它是已由上下文post跟蹤的實體的導航屬性引用的新實體。
using (var context = new BloggingContext()) { //新增一個主體實體 var blog = new Blog { Url = "http://blogs.msdn.com/visualstudio" }; var post = context.Posts.First(); //post更新關系 post.Blog = blog; context.SaveChanges(); }
4.級聯刪除
刪除行為在DeleteBehavior枚舉器類型中定義,并且可以傳遞到OnDelete Fluent API來控制:
- 可以刪除子項/依賴項
- 子項的外鍵值可以設置為null
- 子項保持不變
示例:
var blog = context.Blogs.Include(b => b.Posts).First(); var posts = blog.Posts.ToList(); DumpEntities(" After loading entities:", context, blog, posts); context.Remove(blog); DumpEntities($" After deleting blog '{blog.BlogId}':", context, blog, posts); try { Console.WriteLine(); Console.WriteLine(" Saving changes:"); context.SaveChanges(); DumpSql(); DumpEntities(" After SaveChanges:", context, blog, posts); } catch (Exception e) { DumpSql(); Console.WriteLine(); Console.WriteLine($" SaveChanges threw {e.GetType().Name}: {(e is DbUpdateException ? e.InnerException.Message : e.Message)}"); }
記錄結果:
After loading entities: Blog '1' is in state Unchanged with 2 posts referenced. Post '1' is in state Unchanged with FK '1' and reference to blog '1'. Post '2' is in state Unchanged with FK '1' and reference to blog '1'. After deleting blog '1': Blog '1' is in state Deleted with 2 posts referenced. Post '1' is in state Unchanged with FK '1' and reference to blog '1'. Post '2' is in state Unchanged with FK '1' and reference to blog '1'. Saving changes: DELETE FROM [Posts] WHERE [PostId] = 1 DELETE FROM [Posts] WHERE [PostId] = 2 DELETE FROM [Blogs] WHERE [BlogId] = 1 After SaveChanges: Blog '1' is in state Detached with 2 posts referenced. Post '1' is in state Detached with FK '1' and no reference to a blog. Post '2' is in state Detached with FK '1' and no reference to a blog.
5.事務
事務允許以原子方式處理多個數據庫操作。如果已提交事務,則所有操作都會成功應用到數據庫。如果已回滾事務,則所有操作都不會應用到數據庫。
5.1控制事務
可以使用DbContext.Database API開始、提交和回滾事務。以下示例顯示了兩個SaveChanges()操作以及正在單個事務中執行的LINQ查詢。并非所有數據庫提供應用程序都支持事務的。 調用事務API時,某些提供應用程序可能會引發異常或不執行任何操作。
using (var context = new BloggingContext()) { using (var transaction = context.Database.BeginTransaction()) { try { context.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/dotnet" }); context.SaveChanges(); context.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/visualstudio" }); context.SaveChanges(); var blogs = context.Blogs .OrderBy(b => b.Url) .ToList(); // Commit transaction if all commands succeed, transaction will auto-rollback // when disposed if either commands fails transaction.Commit(); } catch (Exception) { // TODO: Handle failure } } }
原文鏈接:https://www.cnblogs.com/wzk153/p/12449538.html
相關推薦
- 2022-04-08 IIS部署ASP.NET?Core項目及常見問題總結_基礎應用
- 2022-04-06 Python的type函數結果你知道嘛_python
- 2023-02-07 go?reflect要不要傳指針原理詳解_Golang
- 2022-12-04 C#目錄和文件管理操作詳解_C#教程
- 2023-07-08 qt報錯***Fault tolerant heap shim applied to current
- 2022-10-18 Qt?TCP實現簡單通信功能_C 語言
- 2023-01-15 Python?networkx中獲取圖的鄰接矩陣方式_python
- 2022-08-20 python使用tkinter模塊實現文件選擇功能_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支