ASP.NET Core使用EF保存數(shù)據(jù)、級(jí)聯(lián)刪除和事務(wù)使用
1.簡(jiǎn)介
每個(gè)上下文實(shí)例都有一個(gè)ChangeTracker,它負(fù)責(zé)跟蹤需要寫入數(shù)據(jù)庫(kù)的更改。更改實(shí)體類的實(shí)例時(shí),這些更改會(huì)記錄在ChangeTracker中,然后在調(diào)用SaveChanges時(shí)會(huì)被寫入數(shù)據(jù)庫(kù)中。此數(shù)據(jù)庫(kù)提供程序負(fù)責(zé)將更改轉(zhuǎn)換為特定于數(shù)據(jù)庫(kù)的操作(例如,關(guān)系數(shù)據(jù)庫(kù)的INSERT、UPDATE和DELETE命令)。
2.基本保存
了解如何使用上下文和實(shí)體類添加、修改和刪除數(shù)據(jù)。
2.1添加數(shù)據(jù)
使用DbSet.Add方法添加實(shí)體類的新實(shí)例。調(diào)用SaveChanges時(shí),數(shù)據(jù)將插入到數(shù)據(jù)庫(kù)中。
using (var context = new BloggingContext()) { var blog = new Blog { Url = "http://sample.com" }; context.Blogs.Add(blog); context.SaveChanges(); }
2.2更新數(shù)據(jù)
EF將自動(dòng)檢測(cè)對(duì)由上下文跟蹤的現(xiàn)有實(shí)體所做的更改。這包括從數(shù)據(jù)庫(kù)加載查詢的實(shí)體,以及之前添加并保存到數(shù)據(jù)庫(kù)的實(shí)體。只需通過(guò)賦值來(lái)修改屬性,然后調(diào)用SaveChanges即可。
using (var context = new BloggingContext()) { var blog = context.Blogs.First(); blog.Url = "http://sample.com/blog"; context.SaveChanges(); }
2.3刪除數(shù)據(jù)
使用DbSet.Remove方法刪除實(shí)體類的實(shí)例。如果實(shí)體已存在于數(shù)據(jù)庫(kù)中,則將在SaveChanges期間刪除該實(shí)體。如果實(shí)體尚未保存到數(shù)據(jù)庫(kù)(即跟蹤為“已添加”),則在調(diào)用SaveChanges時(shí),該實(shí)體會(huì)從上下文中移除且不再插入。
using (var context = new BloggingContext()) { var blog = context.Blogs.First(); context.Blogs.Remove(blog); context.SaveChanges(); }
2.4單個(gè)SaveChanges中的多個(gè)操作
可以將多個(gè)添加/更新/刪除操作合并到對(duì)SaveChanges的單個(gè)調(diào)用。
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.保存關(guān)聯(lián)數(shù)據(jù)
除了獨(dú)立實(shí)體以外,還可以使用模型中定義的關(guān)系。
3.1添加關(guān)聯(lián)數(shù)據(jù)
如果創(chuàng)建多個(gè)新的相關(guān)實(shí)體,則將其中一個(gè)添加到上下文時(shí)也會(huì)添加其他實(shí)體。在下面的示例中,博客和三個(gè)相關(guān)文章會(huì)全部插入到數(shù)據(jù)庫(kù)中。找到并添加這些文章,因?yàn)樗鼈兛梢酝ㄟ^(guò)Blog.Posts導(dǎo)航屬性訪問(wèn)。
using (var context = new BloggingContext()) { var blog = new Blog { Url = "http://blogs.msdn.com/dotnet", Posts = new List<Post> { 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添加相關(guān)實(shí)體
如果從已由上下文跟蹤的實(shí)體的導(dǎo)航屬性中引用新實(shí)體,則將發(fā)現(xiàn)該實(shí)體并將其插入到數(shù)據(jù)庫(kù)中。在下面的示例中,插入post實(shí)體,因?yàn)樵搶?shí)體會(huì)添加到已從數(shù)據(jù)庫(kù)中提取的blog實(shí)體的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更改關(guān)系
如果更改實(shí)體的導(dǎo)航屬性,則將對(duì)數(shù)據(jù)庫(kù)中的外鍵列進(jìn)行相應(yīng)的更改。在下面的示例中,post實(shí)體更新為屬于新的blog實(shí)體,因?yàn)槠銪log導(dǎo)航屬性設(shè)置為指向blog,blog也會(huì)插入到數(shù)據(jù)庫(kù)中,因?yàn)樗且延缮舷挛膒ost跟蹤的實(shí)體的導(dǎo)航屬性引用的新實(shí)體。
using (var context = new BloggingContext()) { //新增一個(gè)主體實(shí)體 var blog = new Blog { Url = "http://blogs.msdn.com/visualstudio" }; var post = context.Posts.First(); //post更新關(guān)系 post.Blog = blog; context.SaveChanges(); }
4.級(jí)聯(lián)刪除
刪除行為在DeleteBehavior枚舉器類型中定義,并且可以傳遞到OnDelete Fluent API來(lái)控制:
- 可以刪除子項(xiàng)/依賴項(xiàng)
- 子項(xiàng)的外鍵值可以設(shè)置為null
- 子項(xiàng)保持不變
示例:
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)}"); }
記錄結(jié)果:
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.事務(wù)
事務(wù)允許以原子方式處理多個(gè)數(shù)據(jù)庫(kù)操作。如果已提交事務(wù),則所有操作都會(huì)成功應(yīng)用到數(shù)據(jù)庫(kù)。如果已回滾事務(wù),則所有操作都不會(huì)應(yīng)用到數(shù)據(jù)庫(kù)。
5.1控制事務(wù)
可以使用DbContext.Database API開始、提交和回滾事務(wù)。以下示例顯示了兩個(gè)SaveChanges()操作以及正在單個(gè)事務(wù)中執(zhí)行的LINQ查詢。并非所有數(shù)據(jù)庫(kù)提供應(yīng)用程序都支持事務(wù)的。 調(diào)用事務(wù)API時(shí),某些提供應(yīng)用程序可能會(huì)引發(fā)異?;虿粓?zhí)行任何操作。
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 } } }
到此這篇關(guān)于ASP.NET Core使用EF保存數(shù)據(jù)、級(jí)聯(lián)刪除和事務(wù)使用的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- .net如何優(yōu)雅的使用EFCore實(shí)例詳解
- ASP.NET?Core?5.0中的Host.CreateDefaultBuilder執(zhí)行過(guò)程解析
- .Net Core中使用EFCore生成反向工程
- ASP.NET?Core使用EF查詢數(shù)據(jù)
- ASP.NET?Core使用EF創(chuàng)建模型(索引、備用鍵、繼承、支持字段)
- ASP.NET?Core使用EF?SQLite對(duì)數(shù)據(jù)庫(kù)增刪改查
- .net core實(shí)用技巧——將EF Core生成的SQL語(yǔ)句顯示在控制臺(tái)中
- 詳解.Net Core 權(quán)限驗(yàn)證與授權(quán)(AuthorizeFilter、ActionFilterAttribute)
- 在.NET Core類庫(kù)中使用EF Core遷移數(shù)據(jù)庫(kù)到SQL Server的方法
- .net連接oracle的3種實(shí)現(xiàn)方法
- C#利用ODP.net連接Oracle數(shù)據(jù)庫(kù)的操作方法
- .Net使用EF Core框架連接Oracle的方法
相關(guān)文章
asp.net開發(fā)與web標(biāo)準(zhǔn)的沖突問(wèn)題的一些常見(jiàn)解決方法
Visual Studio .net從2003到現(xiàn)在的2008,一路走來(lái)慢慢強(qiáng)大……從以前的vs2003能自動(dòng)改亂你的html代碼到現(xiàn)在在vs2008中都能直接對(duì)html代碼進(jìn)行w3c標(biāo)準(zhǔn)驗(yàn)證并提示了,非常不易。2009-02-02ASP.NET 防止按鈕多次提交核心實(shí)現(xiàn)代碼
防止按鈕多次提交通常都是在注冊(cè)表單中提示時(shí)的一個(gè)小功能,具體實(shí)現(xiàn)如下,由此需求的朋友可以參考下2013-08-08c#后臺(tái)修改前臺(tái)DOM的css屬性示例代碼
本文為大家詳細(xì)介紹下如何使用c#修改前臺(tái)DOM的css屬性,具體示例如下,感興趣的朋友可以參考下哈,希望對(duì)大家有所幫助2013-07-07asp.net Repeater之非常好的數(shù)據(jù)分頁(yè)
asp.net Repeater之非常好的數(shù)據(jù)分頁(yè)實(shí)現(xiàn)代碼。2009-07-07C#后臺(tái)調(diào)用前臺(tái)javascript的五種方法小結(jié)
于項(xiàng)目需要,用到其他項(xiàng)目組用VC開發(fā)的組件,在web后臺(tái)代碼無(wú)法訪問(wèn)這個(gè)組件,所以只好通過(guò)后臺(tái)調(diào)用前臺(tái)的javascript,從而操作這個(gè)組件。2010-12-12ASP.NET MVC錯(cuò)誤處理的對(duì)應(yīng)解決方法
這篇文章主要為大家詳細(xì)介紹了ASP.NET MVC錯(cuò)誤處理的對(duì)應(yīng)解決方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-03-03.Net Core 多文件打包壓縮的實(shí)現(xiàn)代碼
最近項(xiàng)目需要實(shí)現(xiàn)多文件打包的功能,本文就詳細(xì)的介紹了.Net Core 多文件打包壓縮的實(shí)現(xiàn)代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-12-12asp.net SqlParameter關(guān)于Like的傳參數(shù)無(wú)效問(wèn)題
用傳參方式模糊查詢searchName2009-06-06