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

