DAL与小巧玲珑和C#

我有一个利用Dapper的数据访问层,但不禁觉得它可以更加优雅。 DAL只是传递参数并根据模型的命名响应映射模型,因此该部分至少是直接的,但我讨厌看起来重复的代码。

这是一个例子

public IEnumerable ProductSearch(int? userId, DateTime? modifiedAfter, DateTime? modifiedBefore, Guid? productId) { IList products; using (var connection = _connection.OpenConnection()) { const string sproc = "dbo.stp_Product_Search"; products = connection.Query(sproc, new { User_ID = userId, Modified_After = modifiedAfter, Modified_Before = modifiedBefore, Product_ID = productId }, commandType: CommandType.StoredProcedure) .ToList(); } return products; } 

我有很多这样的代码,但使用了不同的参数和实体。 有没有人有任何好的例子?

感谢您的建议。 这就是我最终使用的意思,这意味着每次使用我的类减少代码行时,我不必使用语句来打开连接:

 public class Repository where T : class { protected readonly IComplianceConnection Connection; public Repository(IComplianceConnection connection) { Connection = connection; } public IEnumerable Get(string query, object arguments) { IList entities; using (var connection = Connection.OpenConnection()) { entities = connection.Query(query, arguments, commandType: CommandType.StoredProcedure).ToList(); } return entities; } public T GetSingleOrDefault(string query, object arguments) { T entity; using (var connection = Connection.OpenConnection()) { entity = connection.Query(query, arguments, commandType: CommandType.StoredProcedure).SingleOrDefault(); } return entity; } public void Update(string query, object arguments) { using (var connection = Connection.OpenConnection()) { connection.Execute(query, arguments, commandType: CommandType.StoredProcedure); } } public int ExecuteScalar(string query, object arguments) { var id = 0; using (var connection = Connection.OpenConnection()) { id = connection.ExecuteScalar(query, arguments, commandType: CommandType.StoredProcedure); } return id; } } 

我最近在我的一个项目中使用了Dapper,而且我已经逐渐喜欢它非常简单的事实。 这至少是它如此之快的部分原因。

但我也理解你对重复的看法,如果你从代码中的许多位置调用dbo.stp_Product_Search ,你不希望每次都映射参数并写出整个查询块。

你可以看看将Dapper包装在存储库中,但是我不喜欢这种方法,对我而言,它感觉就像是从我已经成长为喜欢小巧玲珑的裸骨中退了一步。

我会考虑一个经理class。

 public class ProductManager : IProductManager { //Constructor code here public IEnumerable ProductSearch(int? userId, DateTime? modifiedAfter, DateTime? modifiedBefore, Guid? productId) { using (var connection = _connection.OpenConnection()) { const string sproc = "dbo.stp_Product_Search"; return connection.Query(sproc, new { User_ID = userId, Modified_After = modifiedAfter, Modified_Before = modifiedBefore, Product_ID = productId }, commandType: CommandType.StoredProcedure); } } } 

利用上面的类来调用特定于产品的可重用代码。