Exemplo n.º 1
0
        /// <summary>
        /// Saves the <seealso cref="DBObject"/> to the datasource.
        /// </summary>
        /// <param name="saveType">Specifies how to save the <seealso cref="DBObject"/>.</param>
        ///
        /// <example>
        /// The following example shows how to create and saves an <seealso cref="Admin"/> to the datasource.
        /// <code>
        /// Admin admin = new Admin();
        /// admin.Save(DBObject.SaveTypes.Insert);
        /// </code>
        /// </example>
        ///
        /// <example>
        /// The following example shows how to update and save an <seealso cref="Admin"/> currently in the datasource.
        /// <code>
        /// foreach (Admin admin in DBObject.GetAllRecords&lt;Admin&gt;())
        /// {
        ///    if (admin.Username == "user123") // or other unique identifier
        ///    {
        ///       admin.FirstName = "myNewFirstName";
        ///       admin.Save(DBObject.SaveTypes.Update);
        ///    }
        /// }
        /// </code>
        /// </example>
        ///
        /// <returns>
        /// Whether the save was successful or not.
        /// </returns>
        public bool Save(SaveTypes saveType)
        {
            string query;

            switch (saveType)
            {
            case SaveTypes.Insert:
                SetNextPrimaryKey();
                query = CreateInsertString();
                break;

            case SaveTypes.Update:
                query = CreateUpdateString();
                break;

            default:
                throw new NotImplementedException($"SaveType {saveType.ToString()} has not been implemented in the Save method.");
            }
            using (OleDbConnection dbConnection = new OleDbConnection(CONNECTION_STRING))
            {
                using (OleDbCommand command = new OleDbCommand(query, dbConnection))
                {
                    AddValuesToPropertyPlaceholders(command, saveType);
                    dbConnection.Open();
                    return(command.ExecuteNonQuery() == 1);
                }
            }
        }