1.原生MVC EF中,可以使用 System.Transactions 库进行事务的实现

using System.Transactions;
public void TransactionScopeDEMO()
{
    using (TransactionScope transaction = new TransactionScope())
    {
        try
        {
            //todo1
            //todo2
            transaction.Complete(); //只有 Complete 后,才会正式将操作进行提交
        }
        catch (Exception)
        {
            throw;
        }
    }
}

2.通过 SqlTransaction类 进行实现

using System.Data.SqlClient;
public string Transaction()
{
    SqlConnection cnn = new SqlConnection("data source=120.78.128.60;initial catalog=weixinDB;persist security info=True;user id=sa;password=mu101723CRS;");
    cnn.Open();

    SqlCommand cm = new SqlCommand(); 
    SqlTransaction trans = cnn.BeginTransaction();
    
    cm.Connection = cnn;
    cm.Transaction = trans;
   
    try
    { 
        cm.CommandText = "INSERT INTO xxx(xxx) VALUES ('xxx');";
        cm.ExecuteNonQuery(); 

        trans.Commit();
        return "ok";
    }
    catch(Exception e)
    {
        trans.Rollback();
        return e.Message;
    }
    finally
    {
        cnn.Close();
        trans.Dispose();
        cnn.Dispose();
    }
}

3.ABP框架下,通过依赖注入 IUnitOfWorkManager ,虽然默认情况下,数据的提交本身就是一个事务

public class Transaction
{
private readonly IUnitOfWorkManager _unitOfWorkManager;
private readonly IPersonRepository _personRepository;

public MyService(IUnitOfWorkManager unitOfWorkManager, IPersonRepository personRepository)
{
_unitOfWorkManager = unitOfWorkManager;
_personRepository = personRepository;
}

public void CreatePerson(CreatePersonInput input)
{
var person = new Person { Name = input.Name, EmailAddress = input.EmailAddress };
using (var unitOfWork = _unitOfWorkManager.Begin())
{
_personRepository.Insert(person);
unitOfWork.Complete();
}
}
}