最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

1.簡介

每個上下文實例都有一個ChangeTracker,它負責跟蹤需要寫入數(shù)據(jù)庫的更改。更改實體類的實例時,這些更改會記錄在ChangeTracker中,然后在調(diào)用SaveChanges時會被寫入數(shù)據(jù)庫中。此數(shù)據(jù)庫提供程序負責將更改轉(zhuǎn)換為特定于數(shù)據(jù)庫的操作(例如,關系數(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.保存關聯(lián)數(shù)據(jù)

除了獨立實體以外,還可以使用模型中定義的關系。

3.1添加關聯(lián)數(shù)據(jù)

如果創(chuàng)建多個新的相關實體,則將其中一個添加到上下文時也會添加其他實體。在下面的示例中,博客和三個相關文章會全部插入到數(shù)據(jù)庫中。找到并添加這些文章,因為它們可以通過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添加相關實體

如果從已由上下文跟蹤的實體的導航屬性中引用新實體,則將發(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更改關系

如果更改實體的導航屬性,則將對數(shù)據(jù)庫中的外鍵列進行相應的更改。在下面的示例中,post實體更新為屬于新的blog實體,因為其Blog導航屬性設置為指向blog,blog也會插入到數(shù)據(jù)庫中,因為它是已由上下文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.級聯(lián)刪除

刪除行為在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)}");
}

記錄結(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.事務

事務允許以原子方式處理多個數(shù)據(jù)庫操作。如果已提交事務,則所有操作都會成功應用到數(shù)據(jù)庫。如果已回滾事務,則所有操作都不會應用到數(shù)據(jù)庫。

5.1控制事務

可以使用DbContext.Database API開始、提交和回滾事務。以下示例顯示了兩個SaveChanges()操作以及正在單個事務中執(zhí)行的LINQ查詢。并非所有數(shù)據(jù)庫提供應用程序都支持事務的。 調(diào)用事務API時,某些提供應用程序可能會引發(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
        }
    }
}

到此這篇關于ASP.NET Core使用EF保存數(shù)據(jù)、級聯(lián)刪除和事務使用的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

最新評論

罗平县| 易门县| 浪卡子县| 丹凤县| 开封市| 贡嘎县| 宁波市| 沾益县| 玉门市| 三江| 万年县| 太康县| 洛宁县| 菏泽市| 庆安县| 永年县| 鹿泉市| 乡城县| 宜昌市| 上杭县| 安吉县| 乌鲁木齐县| 松滋市| 定远县| 子长县| 三门县| 安徽省| 兴仁县| 财经| 平邑县| 寿阳县| 昌吉市| 苏州市| 田阳县| 长岭县| 荥经县| 安徽省| 揭阳市| 文山县| 朔州市| 巴彦淖尔市|