-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathDynamicQuery.cs
More file actions
197 lines (177 loc) · 7.57 KB
/
DynamicQuery.cs
File metadata and controls
197 lines (177 loc) · 7.57 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
namespace RepoWrapper
{
/// <summary>
/// Dynamic query class.
/// </summary>
public sealed class DynamicQuery
{
/// <summary>
/// Gets the insert query.
/// </summary>
/// <param name="tableName">Name of the table.</param>
/// <param name="item">The item.</param>
/// <returns>
/// The Sql query based on the item properties.
/// </returns>
public static string GetInsertQuery(string tableName, dynamic item)
{
PropertyInfo[] props = item.GetType().GetProperties();
string[] columns = props.Select(p => p.Name).Where(s => s != "ID").ToArray();
return string.Format("INSERT INTO {0} ({1}) OUTPUT inserted.ID VALUES (@{2})",
tableName,
string.Join(",", columns),
string.Join(",@", columns));
}
/// <summary>
/// Gets the update query.
/// </summary>
/// <param name="tableName">Name of the table.</param>
/// <param name="item">The item.</param>
/// <returns>
/// The Sql query based on the item properties.
/// </returns>
public static string GetUpdateQuery(string tableName, dynamic item)
{
PropertyInfo[] props = item.GetType().GetProperties();
string[] columns = props.Select(p => p.Name).ToArray();
var parameters = columns.Select(name => name + "=@" + name).ToList();
return string.Format("UPDATE {0} SET {1} WHERE ID=@ID", tableName, string.Join(",", parameters));
}
/// <summary>
/// Gets the dynamic query.
/// </summary>
/// <param name="tableName">Name of the table.</param>
/// <param name="expression">The expression.</param>
/// <returns>A result object with the generated sql and dynamic params.</returns>
public static QueryResult GetDynamicQuery<T>(string tableName, Expression<Func<T, bool>> expression)
{
var queryProperties = new List<QueryParameter>();
var body = (BinaryExpression) expression.Body;
IDictionary<string, Object> expando = new ExpandoObject();
var builder = new StringBuilder();
// walk the tree and build up a list of query parameter objects
// from the left and right branches of the expression tree
WalkTree(body, ExpressionType.Default, ref queryProperties);
// convert the query parms into a SQL string and dynamic property object
builder.Append("SELECT * FROM ");
builder.Append(tableName);
builder.Append(" WHERE ");
for (int i = 0; i < queryProperties.Count(); i++)
{
QueryParameter item = queryProperties[i];
if (!string.IsNullOrEmpty(item.LinkingOperator) && i > 0)
{
builder.Append(string.Format("{0} {1} {2} @{1} ", item.LinkingOperator, item.PropertyName,
item.QueryOperator));
}
else
{
builder.Append(string.Format("{0} {1} @{0} ", item.PropertyName, item.QueryOperator));
}
expando[item.PropertyName] = item.PropertyValue;
}
return new QueryResult(builder.ToString().TrimEnd(), expando);
}
/// <summary>
/// Walks the tree.
/// </summary>
/// <param name="body">The body.</param>
/// <param name="linkingType">Type of the linking.</param>
/// <param name="queryProperties">The query properties.</param>
private static void WalkTree(BinaryExpression body, ExpressionType linkingType,
ref List<QueryParameter> queryProperties)
{
if (body.NodeType != ExpressionType.AndAlso && body.NodeType != ExpressionType.OrElse)
{
string propertyName = GetPropertyName(body);
dynamic propertyValue = body.Right;
string opr = GetOperator(body.NodeType);
string link = GetOperator(linkingType);
queryProperties.Add(new QueryParameter(link, propertyName, propertyValue.Value, opr));
}
else
{
WalkTree((BinaryExpression) body.Left, body.NodeType, ref queryProperties);
WalkTree((BinaryExpression) body.Right, body.NodeType, ref queryProperties);
}
}
/// <summary>
/// Gets the name of the property.
/// </summary>
/// <param name="body">The body.</param>
/// <returns>The property name for the property expression.</returns>
private static string GetPropertyName(BinaryExpression body)
{
string propertyName = body.Left.ToString().Split(new char[] {'.'})[1];
if (body.Left.NodeType == ExpressionType.Convert)
{
// hack to remove the trailing ) when convering.
propertyName = propertyName.Replace(")", string.Empty);
}
return propertyName;
}
/// <summary>
/// Gets the operator.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>
/// The expression types SQL server equivalent operator.
/// </returns>
/// <exception cref="System.NotImplementedException"></exception>
private static string GetOperator(ExpressionType type)
{
switch (type)
{
case ExpressionType.Equal:
return "=";
case ExpressionType.NotEqual:
return "!=";
case ExpressionType.LessThan:
return "<";
case ExpressionType.GreaterThan:
return ">";
case ExpressionType.AndAlso:
case ExpressionType.And:
return "AND";
case ExpressionType.Or:
case ExpressionType.OrElse:
return "OR";
case ExpressionType.Default:
return string.Empty;
default:
throw new NotImplementedException();
}
}
}
/// <summary>
/// Class that models the data structure in coverting the expression tree into SQL and Params.
/// </summary>
internal class QueryParameter
{
public string LinkingOperator { get; set; }
public string PropertyName { get; set; }
public object PropertyValue { get; set; }
public string QueryOperator { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="QueryParameter" /> class.
/// </summary>
/// <param name="linkingOperator">The linking operator.</param>
/// <param name="propertyName">Name of the property.</param>
/// <param name="propertyValue">The property value.</param>
/// <param name="queryOperator">The query operator.</param>
internal QueryParameter(string linkingOperator, string propertyName, object propertyValue, string queryOperator)
{
this.LinkingOperator = linkingOperator;
this.PropertyName = propertyName;
this.PropertyValue = propertyValue;
this.QueryOperator = queryOperator;
}
}
}