10. Transaction

ef in, savechanges () default transactions.

using (var context = new BookStore())
{
    context.Database.Log = Console.WriteLine;
    Author author1 = new Author() {    Name = "Mark" };
    Author author2 = new Author() {    Name = "John" };
        
    context.Authors.Add(author1);
    context.SaveChanges();
    
    context.Authors.Add(author2);
    context.SaveChanges();
}

 

We can see a transaction to insert two wrap

Opened connection at 10/29/2018 9:18:26 AM +00:00
Started transaction at 10/29/2018 9:18:26 AM +00:00

INSERT [dbo].[Authors]([Name])
VALUES (@0)
SELECT [AuthorId]
FROM [dbo].[Authors]
WHERE @@ROWCOUNT > 0 AND [AuthorId] = scope_identity()

-- @0: 'Mark' (Type = String, Size = -1)
-- Executing at 10/29/2018 9:18:26 AM +00:00
-- Completed in 3 ms with result: SqlDataReader

Committed transaction at 10/29/2018 9:18:26 AM +00:00
Closed connection at 10/29/2018 9:18:26 AM +00:00

Opened connection at 10/29/2018 9:18:26 AM +00:00
Started transaction at 10/29/2018 9:18:26 AM +00:00

INSERT [dbo].[Authors]([Name])
VALUES (@0)
SELECT [AuthorId]
FROM [dbo].[Authors]
WHERE @@ROWCOUNT > 0 AND [AuthorId] = scope_identity()

-- @0: 'John' (Type = String, Size = -1)
-- Executing at 10/29/2018 9:18:26 AM +00:00
-- Completed in 1 ms with result: SqlDataReader

Committed transaction at 10/29/2018 9:18:26 AM +00:00
Closed connection at 10/29/2018 9:18:26 AM +00:00

If you want to perform savechanges several times in a transaction you should write

using (var context = new BookStore())
{
    context.Database.Log = Console.WriteLine;
    using (DbContextTransaction transaction = context.Database.BeginTransaction())
    {
        try
        {
            Author author1 = new Author() {    Name = "Mark" };
            Author author2 = new Author() {    Name = "John" };
            
            context.Authors.Add(author1);
            context.SaveChanges();
            
            context.Authors.Add(author2);
            context.SaveChanges();
            transaction.Commit();
        }
        catch (Exception ex)
        {
            transaction.Rollback();
        }
    }
}
Opened connection at 10/29/2018 9:21:20 AM +00:00
Started transaction at 10/29/2018 9:21:20 AM +00:00

INSERT [dbo].[Authors]([Name])
VALUES (@0)
SELECT [AuthorId]
FROM [dbo].[Authors]
WHERE @@ROWCOUNT > 0 AND [AuthorId] = scope_identity()

-- @0: 'Mark' (Type = String, Size = -1)
-- Executing at 10/29/2018 9:21:20 AM +00:00
-- Completed in 3 ms with result: SqlDataReader

INSERT [dbo].[Authors]([Name])
VALUES (@0)
SELECT [AuthorId]
FROM [dbo].[Authors]
WHERE @@ROWCOUNT > 0 AND [AuthorId] = scope_identity()

-- @0: 'John' (Type = String, Size = -1)
-- Executing at 10/29/2018 9:21:20 AM +00:00
-- Completed in 0 ms with result: SqlDataReader

Committed transaction at 10/29/2018 9:21:20 AM +00:00
Closed connection at 10/29/2018 9:21:20 AM +00:00

 

Guess you like

Origin www.cnblogs.com/nocanstillbb/p/11495042.html