-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathControllerQuery.cs
68 lines (56 loc) · 2.22 KB
/
ControllerQuery.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Text.Json;
using System.Data;
using Microsoft.Data.SqlClient;
using Dapper;
using Microsoft.Extensions.Configuration;
namespace AzureSamples.AzureSQL.Controllers
{
public class ControllerQuery : ControllerBase
{
protected readonly ILogger<ControllerQuery> _logger;
private readonly IConfiguration _config;
public ControllerQuery(IConfiguration config, ILogger<ControllerQuery> logger)
{
_logger = logger;
_config = config;
}
protected async Task<JsonElement> Query(string verb, Type entity, int? id = null,
JsonElement payload = default(JsonElement))
{
JsonDocument result = null;
if (!(new string[] {"get", "put", "patch", "delete"}).Contains(verb.ToLower()))
{
throw new ArgumentException($"verb '{verb}' not supported", nameof(verb));
}
string entityName = entity.Name.Replace("Controller", string.Empty).ToLower();
string procedure = $"dbo.{verb}_{entityName}";
_logger.LogDebug($"Executing {procedure}");
using(var conn = new SqlConnection(_config.GetConnectionString("DefaultConnection"))) {
DynamicParameters parameters = new DynamicParameters();
if (payload.ValueKind != default(JsonValueKind))
{
var json = JsonSerializer.Serialize(payload);
parameters.Add("Json", json);
}
if (id.HasValue)
parameters.Add("Id", id.Value);
var qr = await conn.ExecuteScalarAsync<string>(
sql: procedure,
param: parameters,
commandType: CommandType.StoredProcedure
);
if (qr != null)
result = JsonDocument.Parse(qr);
};
if (result == null)
result = JsonDocument.Parse("[]");
return result.RootElement;
}
}
}