亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

ASP.NET Core使用EF保存數(shù)據(jù)、級(jí)聯(lián)刪除和事務(wù)使用

 更新時(shí)間:2022年04月08日 09:10:53   作者:暗斷腸  
這篇文章介紹了ASP.NET Core使用EF保存數(shù)據(jù)、級(jí)聯(lián)刪除和事務(wù)使用的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

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í)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論