/// <summary> /// Deletes the current <see cref="ORMEntity"/> from the database. /// </summary> public virtual void Delete() { if (!IsNew) { var sqlBuilder = new SQLBuilder(); sqlBuilder.BuildNonQuery(this, NonQueryType.Delete); SQLExecuter.ExecuteNonQuery(sqlBuilder); IsMarkAsDeleted = true; // @Important: // Do we need a ORMEntityState enum? // We need to mark the object as deleted, or it has to be marked as new again. // Something has to be done here, has to be thought out. // -Rick, 25 September 2020 } }
/// <summary> /// Saves the current <see cref="ORMEntity"/> (changes) to the database. /// </summary> public virtual void Save() { if (IsDirty) { var sqlBuilder = new SQLBuilder(); // @Perfomance: it fixes some issues, but this is terrible for the performance. // Needs to be looked at! -Rick, 12 December 2020 foreach (var column in MutableTableScheme) { // When a subEntity is not filled through the parent the PopulateChildEntity method // isn't called and therefore the subEntity is not added to the EntityRelations. if (this[column] != null && this[column].GetType().IsSubclassOf(typeof(ORMEntity))) { var subEntity = Activator.CreateInstance(this[column].GetType().UnderlyingSystemType) as ORMEntity; if (!Relations.Any(x => x.GetType() == subEntity.GetType())) { if ((this[column] as ORMEntity).IsDirty || (OriginalFetchedValue?[column] == null && !(this[column] as ORMEntity).IsDirty)) { Relations.Add(subEntity); } } } } foreach (var relation in Relations) { if (this[relation.GetType().Name] == null && OriginalFetchedValue[relation.GetType().Name] != null) { continue; } else if ((this[relation.GetType().Name] as ORMEntity).IsDirty) { (this[relation.GetType().Name] as ORMEntity).Save(); for (int i = 0; i < relation.PrimaryKey.Count; i++) { var entityRelationId = (int)(this[relation.GetType().Name] as ORMEntity)[relation.PrimaryKey.Keys[i].ColumnName]; var entityJoin = this[relation.GetType().Name]; entityJoin.GetType().GetProperty(relation.PrimaryKey.Keys[i].ColumnName).SetValue(entityJoin, entityRelationId); entityJoin.GetType().GetProperty(nameof(ExecutedQuery)).SetValue(entityJoin, (this[relation.GetType().Name] as ORMEntity).ExecutedQuery); } } } if (IsNew || IsNew && Relations.Any(r => r.IsNew)) { sqlBuilder.BuildNonQuery(this, NonQueryType.Insert); var id = SQLExecuter.ExecuteNonQuery(sqlBuilder); if (PrimaryKey.IsCombinedPrimaryKey) { UpdateCombinedPrimaryKey(); } else { UpdateSinglePrimaryKey(id); } } else { sqlBuilder.BuildNonQuery(this, NonQueryType.Update); SQLExecuter.ExecuteNonQuery(sqlBuilder); } ExecutedQuery = sqlBuilder.GeneratedQuery; } }