Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public bool Create(ISchoolObject thing)
- {
- DataTable table = GetTable(thing);
- string tableName = table.TableName;
- // Get all the properties to be stored for the object
- PropertyInfo[] properties = thing.GetType().GetProperties();
- // Building InsertCommand
- string columns = "";
- string values = "";
- foreach (PropertyInfo property in properties)
- {
- // Don't need the Id property when creating a *new* record since it is auto-incremented
- if (property.Name == "Id")
- continue;
- string prop = property.Name.ToLower();
- columns += prop + ", ";
- values += "@" + prop + ", ";
- command.Parameters.Add("@" + prop, DbType.String, 0, prop);
- }
- // Next two if statements remove the extra ", "
- if(columns != "")
- columns = columns.Remove(columns.Length-2);
- if(values != "")
- values = values.Remove(values.Length-2);
- command.CommandText = "INSERT INTO " + tableName + "(" + columns + ") VALUES(" + values + ")";
- adapter.InsertCommand = command;
- // InsertCommand is ready
- DataRow row = table.Rows.Add();
- Save(thing, properties, row);
- // Setting the Id value of my thing object to the auto-generated id value
- table = GetTable(thing); // This method returns the table in which my object exists in
- int rowCount = table.Rows.Count;
- long id = (long) table.Rows[rowCount - 1]["id"];
- thing.Id = id;
- return true;
- }
- // This method is used for both creating and updating records
- public bool Save(ISchoolObject thing, PropertyInfo[] properties, DataRow row)
- {
- foreach (PropertyInfo property in properties)
- {
- // This loops through every property of the object
- // and then uses the name of the property as the column
- // name and then calls the get method of the property.
- // e.g. row["name"] = thing.Name;
- // Does the above but for every known property automatically
- // The benefits of learning the power of metaprogramming
- // from ruby :-)
- if (property.Name != "Id")
- row[property.Name.ToLower()] = property.GetGetMethod().Invoke(thing, null);
- }
- // This updates the local data set
- adapter.Update(set, GetTableName(thing));
- // This actually saves changes to the
- // dataset to the database
- set.AcceptChanges();
- // Refilling the dataset so the generated
- // id shows up in the dataset
- RefillDataSet(GetTableName(thing));
- return true;
- }
- public void RefillDataSet(string tableName)
- {
- adapter.SelectCommand.CommandText = "SELECT * FROM " + tableName;
- set.Tables[tableName].Clear();
- adapter.Fill(set, tableName);
- }
Advertisement
Add Comment
Please, Sign In to add comment