public static RepositoryResult <T> CheckCreateEntity <T, TId>(
            this BaseDbContext dbAccess,
            T model,
            Func <T, T, bool> isDuplicate = null)
            where T : BaseAuditable <TId>
        {
            var result = new RepositoryResult <T> {
                Entity = model
            };

            // Check 1: model already has unique key - skip
            if (!EqualityComparer <TId> .Default.Equals(model.Id, default))
            {
                result.ResultCode |= RepositoryResultCode.Impractical;
            }

            // Check 2: model does not pass validation - skip
            dbAccess.ValidateEntity <T, TId>(model, result);

            // Check 3: model violated UK constraint
            var baseAuditables = dbAccess.Set <T>().AsEnumerable() ?? new List <T>();

            if (null != isDuplicate && baseAuditables.Any(q => isDuplicate(q, model)))
            {
                result.ResultCode |= RepositoryResultCode.Duplicate;
            }

            return(result);
        }
Esempio n. 2
0
        /// <summary>
        /// Creates an <see cref="RepositoryResult"/> indicating a failed repository operation, with a list of <paramref name="errors"/> if applicable.
        /// </summary>
        /// <param name="errors">An optional array of <see cref="RepositoryResult"/>s which caused the operation to fail.</param>
        /// <returns>An <see cref="RepositoryResult"/> indicating a failed repository operation, with a list of <paramref name="errors"/> if applicable.</returns>
        public static RepositoryResult Failed(params RepositoryError[] errors)
        {
            var result = new RepositoryResult {
                Succeeded = false
            };

            if (errors != null)
            {
                result._errors.AddRange(errors);
            }

            return(result);
        }
        public static void ValidateEntity <T, TId>(this BaseDbContext dbAccess, T entity, RepositoryResult <T> result)
            where T : IAuditable <TId>
        {
            entity.CreatedAt = DateTime.UtcNow;
            entity.CreatedBy = dbAccess.Requestor;

            var validationContext = new ValidationContext(entity);

            if (!Validator.TryValidateObject(entity, validationContext, result.ValidationResult, true))
            {
                result.ResultCode |= RepositoryResultCode.Invalid;
            }
        }