我目前在一个层中有两个类,它们负责将数据插入数据库:
using Dapper;
using System;
using System.Data.SqlClient;
using System.Linq;
namespace repositories
{
public class DAOBook
{
private readonly string _connection;
public DAOBook(string databaseConnection)
{
_connection = databaseConnection;
}
public bool IncludeBook(string title)
{
try
{
using (var connection = new SqlConnection(_connection))
{
var sql = $@"
INSERT INTO books
(title)
VALUES
('{title}' ";
var result = connection.Execute(sql);
return result != 0;
}
}
catch (Exception ex)
{
throw new Exception($"{ex.Message}", ex);
}
}
}
}
using Dapper;
using System;
using System.Data.SqlClient;
using System.Linq;
namespace repositories
{
public class DAOBookTag
{
private readonly string _connection;
public DAOBookTag(string databaseConnection)
{
_connection = databaseConnection;
}
public bool IncludeBookTag(string tag, int userid)
{
try
{
using (var connection = new SqlConnection(_connection))
{
var sql = $@"
INSERT INTO bookTag
(tag, userid)
VALUES
('{tag}', {userid} ";
var result = connection.Execute(sql);
return result != 0;
}
}
catch (Exception ex)
{
throw new Exception($"{ex.Message}", ex);
}
}
}
}
在我的服务层中,我可以正常调用这两个类,并将它们插入到数据库中。
try
{
var connectionString = "<my_connection_string>";
var daoBook = new DAOBook(connectionString);
var daoBookTag = new DAOBookTag(connectionString);
dao.IncludeBook("Alice");
dao.IncludeBookTag("Romance", 1);
}
catch (Exception ex)
{
throw new Exception($"{ex.Message}", ex);
}
然而,我想要加入一个事务控制,以便在插入第二个类时出现错误时,在catch中撤销该事务,就像这样:
try
{
var connectionString = "<my_connection_string>";
var daoBook = new DAOBook(connectionString);
var daoBookTag = new DAOBookTag(connectionString);
// begin transaction
dao.IncludeBook("Alice");
dao.IncludeBookTag("Romance", 1);
// commit
}
catch (Exception ex)
{
// rollback
throw new Exception($"{ex.Message}", ex);
}
我知道这可能是一个初学者的问题,但我似乎找不到两个持久化类共享同一事务的方法。
我看到了一个实现Dapper事务控制的例子,但我不知道如何在我的服务层中实现它(而不是持久化层)。 https://riptutorial.com/dapper/example/22536/using-a-transaction
谢谢