10.事务

ef中,savechanges() 默认使用事务.

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

 

可以看到一个事务把两个insert包起来

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

如果你想在一个事务中多次执行savechanges  你应该这样写

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

 

posted @ 2019-09-09 23:43  马肯尼煤牙巴骨  阅读(174)  评论(0编辑  收藏  举报