DAL与小巧玲珑和C#
发布时间:2020-12-15 23:26:30 所属栏目:百科 来源:网络整理
导读:我有一个利用Dapper的数据访问层,但不禁觉得它可以更加优雅. DAL只是传递参数并根据模型的命名响应映射模型,因此该部分至少是直接的,但我讨厌看起来重复的代码. 这是一个例子 public IEnumerableProduct ProductSearch(int? userId,DateTime? modifiedAfter,
我有一个利用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; } 我有很多这样的代码,但使用了不同的参数和实体.有没有人有任何好的例子? 解决方法
感谢您的建议.这就是我最终使用的意思,这意味着我不必使用语句来编写每次使用少量代码行时打开连接:
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,commandType: CommandType.StoredProcedure).SingleOrDefault(); } return entity; } public void Update(string query,object arguments) { using (var connection = Connection.OpenConnection()) { connection.Execute(query,commandType: CommandType.StoredProcedure); } } public int ExecuteScalar(string query,object arguments) { var id = 0; using (var connection = Connection.OpenConnection()) { id = connection.ExecuteScalar<int>(query,commandType: CommandType.StoredProcedure); } return id; } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容