我有一个使用 Dapper 的数据访问层,但不禁觉得它可以更加优雅。 DAL 只是传递参数并根据模型的命名响应映射模型,因此该部分至少是直接的,但我讨厌看起来重复的代码。
这是一个例子
public IEnumerable<Product> ProductSearch(int? userId, DateTime? modifiedAfter, DateTime? modifiedBefore, Guid? productId)
{
IList<Product> products;
using (var connection = _connection.OpenConnection())
{
const string sproc = "dbo.stp_Product_Search";
products = connection.Query<JobProduct>(sproc, new
{
User_ID = userId,
Modified_After = modifiedAfter,
Modified_Before = modifiedBefore,
Product_ID = productId
}, commandType: CommandType.StoredProcedure)
.ToList();
}
return products;
}
我有很多类似的代码,但使用了不同的参数和实体。有人有什么好的例子吗?
感谢您的建议。这就是我最终使用的方法,意味着我不必每次都编写打开连接的 using 语句,从而使我的类减少代码行数:
public class Repository<T> where T : class
{
protected readonly IComplianceConnection Connection;
public Repository(IComplianceConnection connection)
{
Connection = connection;
}
public IEnumerable<T> Get(string query, object arguments)
{
IList<T> entities;
using (var connection = Connection.OpenConnection())
{
entities = connection.Query<T>(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<T>(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<int>(query, arguments, commandType: CommandType.StoredProcedure);
}
return id;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)