public virtual T Add(T entity) { try { if (entity == null) { throw new ArgumentNullException("entity"); } Entities.Add(entity); _mainDbContext.SaveChanges(); return(entity); } catch (DbEntityValidationException dbEx) { var msg = string.Empty; foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { msg += string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage) + Environment.NewLine; } } var fail = new Exception(msg, dbEx); throw fail; } }
/* * Entity Framework by default wraps Insert, Update or Delete operation in a transaction, whenever you execute SaveChanges() * EF starts a new transaction for each operation and completes the transaction when the operation finishes.When you execute another such operation, a new transaction is started. * EF 6 has introduced database.BeginTransaction and Database.UseTransaction to provide more control over transactions. * Refer: http://www.entityframeworktutorial.net/entityframework6/transaction-in-entity-framework.aspx */ /// <summary> /// Saves all changes made in this context to the underlying database. /// </summary> public void Save() { try { BeginTransaction(); //saves all operations within one transaction _dataContext.SaveChanges(); Commit(); } catch (DbEntityValidationException ex) { foreach (var validationErrors in ex.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { log.ErrorFormat("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } throw; } catch (Exception ex) { log.Error(ex); Rollback(); throw; } }