/// <summary> /// Add a value to the db. /// </summary> /// <param name="settings">The access settings.</param> /// <param name="type">The type to add.</param> /// <param name="item">The item to add.</param> /// <returns>Returns the item id to add, or null if it wasn't.</returns> internal static int?Add(AccessSettings settings, Type type, object item) { AccessTableAttribute typeAttr = type.GetCustomAttribute <AccessTableAttribute>(); int?id = null; if (typeAttr != null) { string columns = string.Empty; string values = string.Empty; Dictionary <string, object> data = new Dictionary <string, object>(); foreach (PropertyInfo prop in type.GetProperties()) { AccessColumnAttribute dataAttr = prop.GetCustomAttribute <AccessColumnAttribute>(); if (dataAttr != null) { if (!dataAttr.IsReadonly) { string cleanName = prop.Name; Object value = prop.GetValue(item); if (value != null) { columns += (string.IsNullOrWhiteSpace(columns) ? "" : ",") + $"[{dataAttr.Name}]"; values += (string.IsNullOrWhiteSpace(values)? "" : ",") + $"@{prop.Name}"; data.Add(prop.Name, value); } } } } AccessWrapper.ExecuteDatabase(settings, $"INSERT INTO [{typeAttr.Table}] ({columns}) VALUES ({values})", data, (command) => { command.ExecuteNonQuery(); id = AccessWrapper.QueryDatabase <int?>(settings, $"SELECT TOP 1 * FROM [{typeAttr.Table}] ORDER BY [{typeAttr.Key}] DESC", (ids) => { ids.Read(); return(ids.GetInt32(0)); }); }); } return(id); }
/// <summary> /// Get a specific object type. /// </summary> /// <param name="settings">The settings to the access database.</param> /// <param name="type">The resulting object type.</param> /// <param name="id">The item id to return, if this has no value return the entire collection.</param> /// <returns>The collection of object.</returns> internal static List <object> Get(AccessSettings settings, Type type, int?id) { AccessTableAttribute attr = type.GetCustomAttribute <AccessTableAttribute>(); List <object> result = null; if (attr != null) { string sql = $"SELECT * FROM [{attr.Table}]"; Dictionary <string, object> data = null; if (id.HasValue) { sql += $" WHERE {attr.Key} = @1"; data = new Dictionary <string, object>() { { "@1", id } }; } result = AccessWrapper.QueryDatabase( settings, sql, data, (reader) => { List <object> output = new List <object>(); while (reader.Read()) { object t = AccessWrapper.Deserialize(type, reader); output.Add(t); } return(output); }); } return(result); }