gpt4 book ai didi

repository-pattern - 如何使用 Dapper 实现工作单元模式?

转载 作者:行者123 更新时间:2023-12-03 07:50:13 24 4
gpt4 key购买 nike

目前,我正在尝试将 Dapper ORM 与工作单元 + 存储库模式一起使用。

我想使用工作单元而不是简单的小巧存储库,因为我的插入和更新需要一定程度的事务处理。我找不到任何有用的示例,因为大多数示例似乎使用 Entity Framework 并且在工作单元中存在泄漏问题。

有人可以指出我正确的方向吗?

最佳答案

对此无需手动解决方案。使用框架中已有的类可以非常简单地实现您想要的。

/// <summary>
/// Register a single instance using whatever DI system you like.
/// </summary>
class ConnectionFactory
{
private string _connectionString;

public ConnectionFactory(string connectionString)
{
_connectionString = connectionString;
}

public IDbConnection CreateConnection()
{
return new SqlConnection(_connectionString);
}
}


/// <summary>
/// Generally, in a properly normalized database, your repos wouldn't map to a single table,
/// but be an aggregate of data from several tables.
/// </summary>
class ProductRepo
{
private ConnectionFactory _connectionFactory;

public ProductRepo(ConnectionFactory connectionFactory)
{
_connectionFactory = connectionFactory;
}

public Product Get(int id)
{
// Allow connection pooling to worry about connection lifetime, that's its job.
using (var con = _connectionFactory.CreateConnection())
{
return con.Get<Product>(id);
}
}

// ...
}

class OrderRepo
{
// As above.
// ...
}

class ProductController : ControllerBase
{
private ProductRepo _productRepo;
private OrderRepo _orderRepo;

public ProductController(ProductRepo productRepo, OrderRepo orderRepo)
{
_productRepo = productRepo;
_orderRepo = orderRepo;
}

[HttpGet]
public Task<IAsyncResult> Get(int id)
{
// This establishes your transaction.
// Default isolation level is 'serializable' which is generally desirable and is configurable.
// Enable async flow option in case subordinate async code results in a thread continuation switch.
// If you don't need this transaction here, don't use it, or put it where it is needed.
using (var trn = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
Product product = _productRepo.Get(id);

// Use additional repositories and do something that actually requires an explicit transaction.
// A single SQL statement does not require a transaction on SQL Server due to default autocommit mode.
// ...

return Ok(product);
}
}
}

关于repository-pattern - 如何使用 Dapper 实现工作单元模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31298235/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com