Exemple #1
0
        /// <summary>
        /// Deletes an object from database. If the object is of type DBObject, then will only set the IsDeleted property to true, otherwise will delete.
        /// </summary>
        /// <typeparam name="T">Type of the entity.</typeparam>
        /// <param name="ctx">Database context instance.</param>
        /// <param name="id">ID of the object to be deleted.</param>
        /// <param name="_commitChanges">If should or not use transaction when deleting.</param>
        /// <returns>Returns an instance of the deleted object.</returns>
        public static T Delete <T>(this CoreDbContext ctx, int id, bool _commitChanges = true) where T : class, IEntity, IKeyed
        {
            var entity = ctx.Find <T>(id);

            if (entity != null)
            {
                if (entity is ITrackableEntity entityTrackable)
                {
                    if (entity.ID > 0)
                    {
                        if (entity is DBObject entityDBObject)
                        {
                            entityDBObject.IsDeleted = true;

                            if (_commitChanges)
                            {
                                ctx.SaveChanges(entityDBObject);
                            }
                            else
                            {
                                ctx.ApplyChanges(entityTrackable);
                            }
                        }
                        else
                        {
                            ctx.Remove(entityTrackable);
                            ctx.SaveChanges();
                        }
                    }
                    else
                    {
                        ctx.RemoveTrackedEntity(entity);
                    }
                }
                else
                {
                    ctx.Remove(entity);
                    ctx.SaveChanges();
                }

                return(entity);
            }
            throw new KeyNotFoundException();
        }