小编sin*_*ase的帖子

如何使用工作单元和存储库模式回滚事务?

我有一个用户存储库,它可以访问所有用户数据.我还有一个工作类单元,用于管理我的存储库的连接和事务.如果我的存储库中发生错误,如何在我的工作单元上有效地回滚事务?

在我的UserRepository上创建方法.我正在使用Dapper进行DataAccess.

try
{
    this.Connection.Execute("User_Create", parameters, this.Transaction, 
        commandType: CommandType.StoredProcedure);
}
catch (Exception)
{
    //Need to tell my unit of work to rollback the transaction.                
}
Run Code Online (Sandbox Code Playgroud)

我将在我的工作单元构造函数中创建的连接和事务传递给我的存储库.以下是我工作单位的财产.

public UserRepository UserRepository
{
    get
    {
        if (this._userRepository == null)
            this._userRepository = 
                new UserRepository(this._connection, this._transaction);
        return this._userRepository;
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望找到最好的方法.

*更新* 在对工作单元模式进行更多研究后,我认为我在我的例子中使用它完全错误.

c# ado.net transactions repository unit-of-work

3
推荐指数
1
解决办法
3423
查看次数

我的数据库连接是否应保持打开并在asp.net中传递或根据需要打开和关闭?

我正在研究一个工作单元,我很好奇应该如何处理连接.我的存储库采用一个工作单元,并将该连接用于Get()命令.

显然,Commit()将处理所有Add,Updates和Deletes.这将打开连接并开始事务并在完成时关闭.如何处理?

应该是UOW,在构造函数中打开连接并在完成时关闭?我将UOW从repo传递到repo时意味着连接已打开.或者我应该只在需要时打开和关闭它?

方法#1:工作单元打开连接并且连接保持打开直到处理完成?

public UnitOfWork(IDbConnection connection)
{
    Connection = connection;
    Connection.Open();
    Transaction = Connection.BeginTransaction();
}
Run Code Online (Sandbox Code Playgroud)

方法#2:在读取之前打开并在之后立即关闭的Get方法的片段.如果传递给多个repos,则使用相同的连接,只需打开和关闭一堆.

 using (var reader = manager.GetReader())
 {
     UOW.Connection.Open();

     while (reader.Read())
         list.Add(factory.CreateTFromReader(reader));

     UOW.Connection.Close();
 }
Run Code Online (Sandbox Code Playgroud)

c# asp.net ado.net

1
推荐指数
1
解决办法
202
查看次数

标签 统计

ado.net ×2

c# ×2

asp.net ×1

repository ×1

transactions ×1

unit-of-work ×1