Exemple #1
0
        /// <summary>
        /// Saves.
        /// </summary>
        /// <param name="value">The entity to add or update.</param>
        /// <param name="cancellationToken">The optional token to monitor for cancellation requests.</param>
        /// <returns>The change method.</returns>
        public virtual async Task <ChangingResultInfo> SaveAsync(T value, CancellationToken cancellationToken = default)
        {
            if (value == null)
            {
                return(new ChangingResultInfo(ChangeMethods.Unchanged));
            }
            var isNew = value.IsNew;

            if (isNew)
            {
                OnAdd(value);
            }
            else
            {
                OnUpdate(value);
            }
            try
            {
                var result = await DbResourceEntityExtensions.SaveAsync(Set, SaveChangesAsync, value, cancellationToken);

                Saved?.Invoke(this, new ChangeEventArgs <T>(isNew ? null : value, value, result));
                if (ResourceEntityExtensions.IsSuccessful(result))
                {
                    return(new ChangingResultInfo <T>(result, value, $"{result} {typeof(T).Name} entity."));
                }
                return(result);
            }
            catch (Exception ex)
            {
                var err = DbResourceEntityExtensions.TryCatch(ex);
                if (err != null)
                {
                    return(err);
                }
                throw;
            }
        }
 /// <summary>
 /// Creates or updates an entity.
 /// </summary>
 /// <typeparam name="T">The type of entity.</typeparam>
 /// <param name="set">The entity set.</param>
 /// <param name="save">The save action handler.</param>
 /// <param name="entity">The entity.</param>
 /// <param name="cancellationToken">The optional token to monitor for cancellation requests.</param>
 /// <returns>An async task result.</returns>
 public static Task <ChangeMethods> SaveAsync <T>(DbSet <T> set, Func <CancellationToken, Task <int> > save, T entity, CancellationToken cancellationToken = default) where T : BaseResourceEntity
 {
     InternalAssertion.IsNotNull(set, nameof(set));
     return(ResourceEntityExtensions.SaveAsync(entity, set.Add, set.Update, save, cancellationToken));
 }