(26) ASP.NET Core EF save (basic save, save data, cascading deletes, use transaction)

1 Introduction

Each context instance has a ChangeTracker, which is responsible for tracking changes need to be written to the database. When you change the type of entity instances, these changes are recorded in the ChangeTracker, and then when you call SaveChanges will be written to the database. This database provider is responsible for converting specific changes to the operation of the database (for example, INSERT relational database, UPDATE, and DELETE commands).

2. Basic Save

Learn how to use context and entity classes to add, modify and delete data.

2.1 Adding Data

Add a new instance of the entity class using DbSet.Add method. When you call SaveChanges, the data will be inserted into the database.

using (var context = new BloggingContext())
{
    var blog = new Blog { Url = "http://sample.com" };
    context.Blogs.Add(blog);
    context.SaveChanges();
}

2.2 update data

EF automatically detects changes to the existing entity tracked by the context. This includes entities loaded from the database query, as well as add and save entity to database before. Simply by assigning attributes to modify, and then call SaveChanges can be.

using (var context = new BloggingContext())
{
    var blog = context.Blogs.First();
    blog.Url = "http://sample.com/blog";
    context.SaveChanges();
}

2.3 to delete data

Use DbSet.Remove method to remove instance of an entity class. If the entity already exists in the database, then delete the entity during SaveChanges. If the entity has not been saved to the database (that is, tracking is "Added"), when you call SaveChanges, the entity will be removed from the context and is no longer inserted.

using (var context = new BloggingContext())
{
    var blog = context.Blogs.First();
    context.Blogs.Remove(blog);
    context.SaveChanges();
}

2.4 a plurality of operations in a single SaveChanges

More you can add / update / delete operations into a single call to the 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. Save Linked Data

In addition to an independent entity, but also the relationship defined in the model can be used.

3.1 Adding associated data

If you also add other entities to create multiple new related entities, one of which will be added to the context. In the following example, the blog and all three related articles will be inserted into the database. Find and add these articles, because they can be accessed through the navigation property 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 Adding related entities

If the reference from the new entity navigation context attributes of the entity has been tracked, the entity will be found and inserted into the database. In the following example, the insertion post entity as the entity is added to the blog Posts entity attributes extracted from the database.

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 Changing Relationship

If you change the navigation attributes of the entity, then the foreign key in the database changes the corresponding column. In the following example, to update an entity belonging to post new blog entity because of its property to point navigation Blog blog, the blog will be inserted into the database, because it is the context of post track navigation property has been cited new entity entity.

the using ( var context = new new BloggingContext ()) 
{ 
    // add an entity body 
    var Blog = new new Blog the Url = { " http://blogs.msdn.com/visualstudio " };
     var POST = context.Posts.First ( );
     // POST update the relational 
    post.Blog = Blog; 
    context.SaveChanges (); 
}

4. cascade delete

Remove behavior DeleteBehavior enumerator type definitions, and may be transmitted to the controlling OnDelete Fluent API:
● can remove the child / dependency
● child foreign key value may be set to null
● child unchanged
Example:

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)}");
}

Record results:

 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. Transaction

Transaction atomically process allows a plurality of database operations. If the transaction is committed, all operations will be successfully applied to the database. If the transaction is rolled back, then all operations are not applied to the database.

5.1 Control Transactions

DbContext.Database API can be used to start, commit and rollback transactions. The following example shows two LINQ query the SaveChanges () operation, and is performed in a single transaction. Not all databases provide applications support transactions. When you call the transaction API, providing some application may throw an exception or do nothing.

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. Summary

As busy reason, EF series here will come to an end, temporarily do not have much time to go on record. Today, this chapter also stole a lazy, a little more concise, specific official explanation, I will paste below, please forgive me.

References:
Basic Save
to save the relevant data
cascade delete
using transactions

Guess you like

Origin www.cnblogs.com/wzk153/p/12449538.html