日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

ASP.NET?Core使用EF保存數據、級聯刪除和事務使用_實用技巧

作者:暗斷腸 ? 更新時間: 2022-06-10 編程語言

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

欄目分類
最近更新