1. 程式人生 > >(26)ASP.NET Core EF儲存(基本儲存、儲存相關資料、級聯刪除、使用事務)

(26)ASP.NET Core EF儲存(基本儲存、儲存相關資料、級聯刪除、使用事務)

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<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新增相關實體

如果從已由上下文跟蹤的實體的導航屬性中引用新實體,則將發現該實體並將其插入到資料庫中。在下面的示例中,插入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
        }
    }
}

6.總結

由於工作繁忙原因,EF系列在這裡也就完結了,暫時沒有太多時間記錄下去了。今天這個章節也偷了個懶,稍微精簡一點,具體官方說明,我會在下面貼上的,請見諒。

參考文獻:
基本儲存
儲存相關資料
級聯刪除
使用