/// <summary> /// Deletes an object from the json file db /// </summary> /// <typeparam name="T"></typeparam> /// <param name="model">Object to delete</param> public void Delete <T>(IJsonDbEntity model) { if (model == null) { throw new Exception("model cannot be of null value"); } string newJson = String.Empty; var fi = GetDataFile <T>(); var json = File.ReadAllText(fi.ToString()); // if the file is empty write out the data if (!String.IsNullOrEmpty(json)) { // deserialze json into our collection var db = JsonConvert.DeserializeObject <List <T> >(json, JsonSerializerSettings); // cast it to IEntity so we can get by id var data = db.Cast <IJsonDbEntity>().ToList(); // we delete it var obj = data.RemoveAll(x => x.Id == model.Id); // serialize it back newJson = JsonConvert.SerializeObject(data); } // save SaveData(fi, newJson); }
/// <summary> /// Get object by Id /// </summary> /// <typeparam name="T"></typeparam> /// <param name="id">Object Id</param> public T Get <T>(int id) { var json = File.ReadAllText(GetDataFile <T>().ToString()); var db = JsonConvert.DeserializeObject <List <T> >(json, JsonSerializerSettings); // cast it to IEntity so we can get by id var data = db.Cast <IJsonDbEntity>().ToDictionary(x => x.Id, x => x); // get the object by id IJsonDbEntity row = null; var obj = data.TryGetValue(id, out row); return((T)row); }