Permalink
Browse files

A more elegant solution to the expando issue

  • Loading branch information...
1 parent 25d24c7 commit 26621bce7b9d74dde9af75a459d24b4bd3e47cbb @subsonic subsonic committed Sep 27, 2011
Showing with 31 additions and 3 deletions.
  1. +31 −3 Massive.cs
View
@@ -88,6 +88,21 @@ public static class ObjectExtensions {
return (IDictionary<string, object>)thingy.ToExpando();
}
}
+
+ /// <summary>
+ /// Convenience class for opening/executing data
+ /// </summary>
+ public static class DB {
+ public static DynamicModel Current {
+ get {
+ if (ConfigurationManager.ConnectionStrings.Count > 1) {
+ return new DynamicModel(ConfigurationManager.ConnectionStrings[1].Name);
+ }
+ throw new InvalidOperationException("Need a connection string name - can't determine what it is");
+ }
+ }
+ }
+
/// <summary>
/// A class that wraps your database table in Dynamic Funtime
/// </summary>
@@ -457,8 +472,8 @@ public class DynamicModel : DynamicObject {
throw new InvalidOperationException("Can't insert: " + String.Join("; ", Errors.ToArray()));
}
if (BeforeSave(ex)) {
- using (var conn = OpenConnection()) {
- var cmd = CreateInsertCommand((ExpandoObject)ex);
+ using (dynamic conn = OpenConnection()) {
+ var cmd = CreateInsertCommand(ex);
cmd.Connection = conn;
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT @@IDENTITY as newID";
@@ -481,7 +496,7 @@ public class DynamicModel : DynamicObject {
}
var result = 0;
if (BeforeSave(ex)) {
- result = Execute(CreateUpdateCommand((ExpandoObject)ex, key));
+ result = Execute(CreateUpdateCommand(ex, key));
Updated(ex);
}
return result;
@@ -499,6 +514,13 @@ public class DynamicModel : DynamicObject {
return result;
}
+ public void DefaultTo(string key, object value, dynamic item) {
+ if (!ItemContainsKey(key, item)) {
+ var dc = (IDictionary<string, object>)item;
+ dc[key] = value;
+ }
+ }
+
//Hooks
public virtual void Validate(dynamic item) { }
public virtual void Inserted(dynamic item) { }
@@ -532,6 +554,12 @@ public class DynamicModel : DynamicObject {
}
+ public int Count() {
+ return Count(TableName);
+ }
+ public int Count(string tableName, string where="") {
+ return (int)Scalar("SELECT COUNT(*) FROM " + tableName);
+ }
/// <summary>
/// A helpful query tool

0 comments on commit 26621bc

Please sign in to comment.