예제 #1
0
        public void Add(ref TEntity entity)
        {
            try
            {
                DbSet.Add(entity);
                _context.SaveChanges();
            }
            catch (DbUpdateException dbEx)
            {
                var entry = _context.Entry(entity);
                if (entry.State == EntityState.Added)
                {
                    DbSet.Remove(entity);
                }
                CustomDbExceptionHandler.ThrowHandledError(dbEx);
                throw;
            }
            catch (DbEntityValidationException ex)
            {
                // Retrieve the error messages as a list of strings.
                var errorMessages = ex.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.ErrorMessage);

                // Join the list to a single string.
                var fullErrorMessage = string.Join("; ", errorMessages);

                // Combine the original exception message with the new one.
                var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);

                // Throw a new DbEntityValidationException with the improved exception message.
                throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
            }
        }
예제 #2
0
 public void Delete(object id)
 {
     try
     {
         var entity = DbSet.Find(id);
         DbSet.Remove(entity);
         _context.SaveChanges();
     }
     catch (DbUpdateException dbEx)
     {
         CustomDbExceptionHandler.ThrowHandledError(dbEx);
         throw;
     }
 }
예제 #3
0
 public void Update(TEntity entity)
 {
     try
     {
         DbSet.AsNoTracking();
         _context.Entry(entity).State = EntityState.Modified;
         _context.SaveChanges();
     }
     catch (DbUpdateException dbEx)
     {
         CustomDbExceptionHandler.ThrowHandledError(dbEx);
         throw;
     }
 }