Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Removed Fetch - redundant. Added overload for passing in a connection…

… to Query. Refactored reader assignment to use single method. LOC is same
  • Loading branch information...
commit 1b4d7c735cf744ab19929afc0967e9c71682771f 1 parent eef91b4
SubSonic Project subsonic authored

Showing 1 changed file with 45 additions and 44 deletions. Show diff stats Hide diff stats

  1. +45 44 Massive.cs
89 Massive.cs
@@ -33,7 +33,7 @@ public static class ObjectExtensions {
33 33 p.Value = item.ToString();
34 34 p.DbType = DbType.String;
35 35 p.Size = 4000;
36   - }else if(item.GetType()==typeof(ExpandoObject)){
  36 + } else if (item.GetType() == typeof(ExpandoObject)) {
37 37 var d = (IDictionary<string, object>)item;
38 38 p.Value = d.Values.FirstOrDefault();
39 39 } else {
@@ -51,14 +51,17 @@ public static class ObjectExtensions {
51 51 public static List<dynamic> ToExpandoList(this IDataReader rdr) {
52 52 var result = new List<dynamic>();
53 53 while (rdr.Read()) {
54   - dynamic e = new ExpandoObject();
55   - var d = e as IDictionary<string, object>;
56   - for (int i = 0; i < rdr.FieldCount; i++)
57   - d.Add(rdr.GetName(i), rdr[i]);
58   - result.Add(e);
  54 + result.Add(rdr.RecordToExpando());
59 55 }
60 56 return result;
61 57 }
  58 + public static dynamic RecordToExpando(this IDataReader rdr) {
  59 + dynamic e = new ExpandoObject();
  60 + var d = e as IDictionary<string, object>;
  61 + for (int i = 0; i < rdr.FieldCount; i++)
  62 + d.Add(rdr.GetName(i), rdr[i]);
  63 + return e;
  64 + }
62 65 /// <summary>
63 66 /// Turns the object into an ExpandoObject
64 67 /// </summary>
@@ -66,7 +69,7 @@ public static class ObjectExtensions {
66 69 var result = new ExpandoObject();
67 70 var d = result as IDictionary<string, object>; //work with the Expando as a Dictionary
68 71 if (o.GetType() == typeof(ExpandoObject)) return o; //shouldn't have to... but just in case
69   - if (o.GetType() == typeof(NameValueCollection) || o.GetType().IsSubclassOf(typeof(NameValueCollection))){
  72 + if (o.GetType() == typeof(NameValueCollection) || o.GetType().IsSubclassOf(typeof(NameValueCollection))) {
70 73 var nv = (NameValueCollection)o;
71 74 nv.Cast<string>().Select(key => new KeyValuePair<string, object>(key, nv[key])).ToList().ForEach(i => d.Add(i));
72 75 } else {
@@ -87,12 +90,12 @@ public static class ObjectExtensions {
87 90 /// <summary>
88 91 /// A class that wraps your database table in Dynamic Funtime
89 92 /// </summary>
90   - public class DynamicModel {
  93 + public class DynamicModel {
91 94 DbProviderFactory _factory;
92 95 string _connectionString;
93 96
94   - public DynamicModel(string connectionStringName= "", string tableName = "", string primaryKeyField ="") {
95   - TableName = tableName == "" ? this.GetType().Name : tableName;
  97 + public DynamicModel(string connectionStringName = "", string tableName = "", string primaryKeyField = "") {
  98 + TableName = tableName == "" ? this.GetType().Name : tableName;
96 99 PrimaryKeyField = string.IsNullOrEmpty(primaryKeyField) ? "ID" : primaryKeyField;
97 100 if (connectionStringName == "")
98 101 connectionStringName = ConfigurationManager.ConnectionStrings[0].Name;
@@ -111,21 +114,19 @@ public class DynamicModel {
111 114 /// </summary>
112 115 public virtual IEnumerable<dynamic> Query(string sql, params object[] args) {
113 116 using (var conn = OpenConnection()) {
114   - var rdr = CreateCommand(sql, conn, args).ExecuteReader(CommandBehavior.CloseConnection);
  117 + var rdr = CreateCommand(sql, conn, args).ExecuteReader();
115 118 while (rdr.Read()) {
116   - var e = new ExpandoObject();
117   - var d = e as IDictionary<string, object>;
118   - for (var i = 0; i < rdr.FieldCount; i++)
119   - d.Add(rdr.GetName(i), rdr[i]);
120   - yield return e;
  119 + yield return rdr.RecordToExpando(); ;
121 120 }
122 121 }
123 122 }
124   - /// <summary>
125   - /// Runs a query against the database
126   - /// </summary>
127   - public virtual IList<dynamic> Fetch(string sql, params object[] args) {
128   - return Query(sql, args).ToList<dynamic>();
  123 + public virtual IEnumerable<dynamic> Query(string sql, DbConnection connection, params object[] args) {
  124 + using (var rdr = CreateCommand(sql, connection, args).ExecuteReader()) {
  125 + while (rdr.Read()) {
  126 + yield return rdr.RecordToExpando(); ;
  127 + }
  128 + }
  129 +
129 130 }
130 131 /// <summary>
131 132 /// Returns a single result
@@ -136,13 +137,12 @@ public class DynamicModel {
136 137 result = CreateCommand(sql, conn, args).ExecuteScalar();
137 138 }
138 139 return result;
139   - }
  140 + }
140 141 /// <summary>
141 142 /// Creates a DBCommand that you can use for loving your database.
142 143 /// </summary>
143 144 DbCommand CreateCommand(string sql, DbConnection conn, params object[] args) {
144   - DbCommand result = null;
145   - result = _factory.CreateCommand();
  145 + var result = _factory.CreateCommand();
146 146 result.Connection = conn;
147 147 result.CommandText = sql;
148 148 if (args.Length > 0)
@@ -153,10 +153,10 @@ public class DynamicModel {
153 153 /// Returns and OpenConnection
154 154 /// </summary>
155 155 public virtual DbConnection OpenConnection() {
156   - var conn = _factory.CreateConnection();
157   - conn.ConnectionString = _connectionString;
158   - conn.Open();
159   - return conn;
  156 + var result = _factory.CreateConnection();
  157 + result.ConnectionString = _connectionString;
  158 + result.Open();
  159 + return result;
160 160 }
161 161 /// <summary>
162 162 /// Builds a set of Insert and Update commands based on the passed-on objects.
@@ -167,8 +167,8 @@ public class DynamicModel {
167 167 var commands = new List<DbCommand>();
168 168 foreach (var item in things) {
169 169 if (HasPrimaryKey(item)) {
170   - commands.Add(CreateUpdateCommand(item,GetPrimaryKey(item)));
171   - }else{
  170 + commands.Add(CreateUpdateCommand(item, GetPrimaryKey(item)));
  171 + } else {
172 172 commands.Add(CreateInsertCommand(item));
173 173 }
174 174 }
@@ -197,7 +197,7 @@ public class DynamicModel {
197 197 foreach (var cmd in commands) {
198 198 cmd.Connection = conn;
199 199 cmd.Transaction = tx;
200   - result+=cmd.ExecuteNonQuery();
  200 + result += cmd.ExecuteNonQuery();
201 201 }
202 202 tx.Commit();
203 203 }
@@ -232,7 +232,7 @@ public class DynamicModel {
232 232 var sbKeys = new StringBuilder();
233 233 var sbVals = new StringBuilder();
234 234 var stub = "INSERT INTO {0} ({1}) \r\n VALUES ({2})";
235   - result = CreateCommand(stub,null);
  235 + result = CreateCommand(stub, null);
236 236 int counter = 0;
237 237 foreach (var item in settings) {
238 238 sbKeys.AppendFormat("{0},", item.Key);
@@ -257,7 +257,7 @@ public class DynamicModel {
257 257 var sbKeys = new StringBuilder();
258 258 var stub = "UPDATE {0} SET {1} WHERE {2} = @{3}";
259 259 var args = new List<object>();
260   - var result = CreateCommand(stub,null);
  260 + var result = CreateCommand(stub, null);
261 261 int counter = 0;
262 262 foreach (var item in settings) {
263 263 var val = item.Value;
@@ -283,10 +283,10 @@ public class DynamicModel {
283 283 var sql = string.Format("DELETE FROM {0} ", TableName);
284 284 if (key != null) {
285 285 sql += string.Format("WHERE {0}=@0", PrimaryKeyField);
286   - args = new object[]{key};
  286 + args = new object[] { key };
287 287 } else if (!string.IsNullOrEmpty(where)) {
288 288 sql += where.Trim().StartsWith("where", StringComparison.CurrentCultureIgnoreCase) ? where : "WHERE " + where;
289   - }
  289 + }
290 290 return CreateCommand(sql, null, args);
291 291 }
292 292 /// <summary>
@@ -315,7 +315,7 @@ public class DynamicModel {
315 315 /// Removes one or more records from the DB according to the passed-in WHERE
316 316 /// </summary>
317 317 public int Delete(object key = null, string where = "", params object[] args) {
318   - return Execute(CreateDeleteCommand(where: where, key:key, args: args));
  318 + return Execute(CreateDeleteCommand(where: where, key: key, args: args));
319 319 }
320 320 /// <summary>
321 321 /// Returns all records complying with the passed-in WHERE clause and arguments,
@@ -327,13 +327,13 @@ public class DynamicModel {
327 327 sql += where.Trim().StartsWith("where", StringComparison.CurrentCultureIgnoreCase) ? where : "WHERE " + where;
328 328 if (!String.IsNullOrEmpty(orderBy))
329 329 sql += orderBy.Trim().StartsWith("order by", StringComparison.CurrentCultureIgnoreCase) ? orderBy : " ORDER BY " + orderBy;
330   - return Query(string.Format(sql, columns,TableName), args);
  330 + return Query(string.Format(sql, columns, TableName), args);
331 331 }
332 332
333 333 /// <summary>
334 334 /// Returns a dynamic PagedResult. Result properties are Items, TotalPages, and TotalRecords.
335 335 /// </summary>
336   - public virtual dynamic Paged(string where = "", string orderBy = "", string columns = "*", int pageSize = 20, int currentPage =1, params object[] args) {
  336 + public virtual dynamic Paged(string where = "", string orderBy = "", string columns = "*", int pageSize = 20, int currentPage = 1, params object[] args) {
337 337 dynamic result = new ExpandoObject();
338 338 var countSQL = string.Format("SELECT COUNT({0}) FROM {1}", PrimaryKeyField, TableName);
339 339 if (String.IsNullOrEmpty(orderBy))
@@ -344,11 +344,11 @@ public class DynamicModel {
344 344 where = "WHERE " + where;
345 345 }
346 346 }
347   - var sql = string.Format("SELECT {0} FROM (SELECT ROW_NUMBER() OVER (ORDER BY {2}) AS Row, {0} FROM {3} {4}) AS Paged ",columns,pageSize,orderBy,TableName, where);
348   - var pageStart = (currentPage -1) * pageSize;
349   - sql+= string.Format(" WHERE Row >={0} AND Row <={1}",pageStart, (pageStart + pageSize));
  347 + var sql = string.Format("SELECT {0} FROM (SELECT ROW_NUMBER() OVER (ORDER BY {2}) AS Row, {0} FROM {3} {4}) AS Paged ", columns, pageSize, orderBy, TableName, where);
  348 + var pageStart = (currentPage - 1) * pageSize;
  349 + sql += string.Format(" WHERE Row >={0} AND Row <={1}", pageStart, (pageStart + pageSize));
350 350 countSQL += where;
351   - result.TotalRecords = Scalar(countSQL,args);
  351 + result.TotalRecords = Scalar(countSQL, args);
352 352 result.TotalPages = result.TotalRecords / pageSize;
353 353 if (result.TotalRecords % pageSize > 0)
354 354 result.TotalPages += 1;
@@ -359,8 +359,9 @@ public class DynamicModel {
359 359 /// Returns a single row from the database
360 360 /// </summary>
361 361 public virtual dynamic Single(object key, string columns = "*") {
362   - var sql = string.Format("SELECT {0} FROM {1} WHERE {2} = @0", columns,TableName, PrimaryKeyField);
363   - return Fetch(sql, key).FirstOrDefault();
  362 + var sql = string.Format("SELECT {0} FROM {1} WHERE {2} = @0", columns, TableName, PrimaryKeyField);
  363 + var items = Query(sql, key).ToList();
  364 + return items.FirstOrDefault();
364 365 }
365 366 }
366 367 }

0 comments on commit 1b4d7c7

Please sign in to comment.
Something went wrong with that request. Please try again.