-
Notifications
You must be signed in to change notification settings - Fork 0
/
SQLMonkey.cs
59 lines (50 loc) · 2.15 KB
/
SQLMonkey.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
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SQLMonkey {
class SQLMonkey {
public string connectionString { get; set; }
public SQLMonkey(string connectionString) {
this.connectionString = connectionString;
}
private void executeScalarQuery(string sqlQuery) {
using (var connection = new SqlConnection(connectionString)) {
connection.Open();
var command = new SqlCommand(sqlQuery, connection);
command.ExecuteScalar();
}
}
public void insert<T>(T instance, string tableName) {
var sqlQuery = SQLGeneration.generateInsertQuery<T>(instance, tableName);
executeScalarQuery(sqlQuery);
}
public void update<T>(T instance, string tableName) {
var sqlQuery = SQLGeneration.generateUpdateQuery<T>(instance, tableName);
executeScalarQuery(sqlQuery);
}
public void delete<T>(T instance, string tableName) {
var sqlQuery = SQLGeneration.generateDeleteQuery<T>(instance, tableName);
executeScalarQuery(sqlQuery);
}
public IEnumerable<T> retrieve<T>(string tableName) {
var sqlQuery = SQLGeneration.generateRetrieveQuery(tableName);
using (var connection = new SqlConnection(connectionString)) {
connection.Open();
var command = new SqlCommand(sqlQuery, connection);
using (SqlDataReader reader = command.ExecuteReader()) {
while (reader.Read()) {
var instance = (T)Activator.CreateInstance(typeof(T));
var propValuePairs = instance.GetType().GetProperties().Select(x => x.Name);
foreach (var prop in propValuePairs) {
instance.GetType().GetProperty(prop).SetValue(instance, reader[prop], null);
}
yield return instance;
}
}
}
}
}
}