| | | 1 | | using System.Data.Common; |
| | | 2 | | using System.Data; |
| | | 3 | | |
| | | 4 | | namespace Snacks.DAL.Common; |
| | | 5 | | |
| | | 6 | | public delegate T RowMapper<T>(IDataRecord row); |
| | | 7 | | |
| | | 8 | | public class AdoTemplate : IAdoTemplate |
| | | 9 | | { |
| | | 10 | | private readonly IConnectionFactory connectionFactory; |
| | | 11 | | |
| | | 12 | | private void AddParameters(DbCommand command, QueryParameter[] parameters) |
| | 328 | 13 | | { |
| | 3432 | 14 | | foreach (var p in parameters) |
| | 1224 | 15 | | { |
| | 1224 | 16 | | DbParameter dbParameter = command.CreateParameter(); |
| | 1224 | 17 | | dbParameter.ParameterName = p.Name; |
| | 1224 | 18 | | dbParameter.Value = p.Value; |
| | 1224 | 19 | | command.Parameters.Add(dbParameter); |
| | 1224 | 20 | | } |
| | 328 | 21 | | } |
| | | 22 | | |
| | 256 | 23 | | public AdoTemplate(IConnectionFactory connectionFactory) |
| | 256 | 24 | | { |
| | 256 | 25 | | this.connectionFactory = connectionFactory; |
| | 256 | 26 | | } |
| | | 27 | | |
| | | 28 | | public async Task<IEnumerable<T>> QueryAsync<T>(string sql, RowMapper<T> rowMapper, params QueryParameter[] paramete |
| | 186 | 29 | | { |
| | 186 | 30 | | await using DbConnection connection = await connectionFactory.CreateConnectionAsync(); |
| | | 31 | | |
| | 186 | 32 | | await using DbCommand command = connection.CreateCommand(); |
| | 186 | 33 | | command.CommandText = sql; |
| | 186 | 34 | | AddParameters(command, parameters); |
| | 186 | 35 | | await using DbDataReader reader = await command.ExecuteReaderAsync(); |
| | | 36 | | |
| | 186 | 37 | | List<T> items = new List<T>(); |
| | 390 | 38 | | while (await reader.ReadAsync()) |
| | 204 | 39 | | { |
| | 204 | 40 | | items.Add((T)rowMapper(reader)); |
| | 204 | 41 | | } |
| | 186 | 42 | | return items; |
| | 186 | 43 | | } |
| | | 44 | | |
| | | 45 | | public async Task<int> ExecuteAsync(string sql,params QueryParameter[] parameters) |
| | 142 | 46 | | { |
| | 142 | 47 | | await using DbConnection connection = await connectionFactory.CreateConnectionAsync(); |
| | | 48 | | |
| | 142 | 49 | | await using DbCommand command = connection.CreateCommand(); |
| | 142 | 50 | | command.CommandText = sql; |
| | 142 | 51 | | AddParameters(command, parameters); |
| | | 52 | | |
| | 142 | 53 | | return await command.ExecuteNonQueryAsync(); |
| | 142 | 54 | | } |
| | | 55 | | |
| | | 56 | | } |