public void CloseTransaction(Exception exception) { try { if (_currentTransaction != null && exception != null) { // todo: log exception _currentTransaction.Rollback(); return; } SaveChanges(); _currentTransaction?.Commit(); } catch (Exception) { if (_currentTransaction?.UnderlyingTransaction.Connection != null) { _currentTransaction.Rollback(); } throw; } finally { if (_currentTransaction != null) { _currentTransaction.Dispose(); _currentTransaction = null; } } }
public bool CommitTransaction() { bool success = true; lock (lockObject) { try { SaveChanges(false); dbTransaction?.Commit(); dbTransaction?.Dispose(); dbTransaction = null; } catch (System.Data.Entity.Infrastructure.DbUpdateException) { dbTransaction = clientContext.Database.CurrentTransaction; success = false; } } if (success) { PerformSaveActions(); } saveActions.Clear(); return(success); }
/// <summary> /// Save change into database. /// </summary> /// <returns></returns> public override int Commit() { int result; try { //result = GetListRepository().Sum(repositoryBase => repositoryBase.Commit()); result = DataContext.SaveChanges(); _transaction?.Commit(); _transaction?.Dispose(); _transaction = null; IList <IRepositoryBase> listRepositoryBases = GetAllRepository(); foreach (IRepositoryBase repositoryBase in listRepositoryBases) { repositoryBase.HasTransaction = true; } } catch (System.Exception) { _transaction?.Rollback(); _transaction?.Dispose(); _transaction = null; IList <IRepositoryBase> listRepositoryBases = GetAllRepository(); foreach (IRepositoryBase repositoryBase in listRepositoryBases) { repositoryBase.HasTransaction = true; } throw; } return(result); }
public void CommitTransaction() { if (!_transactionClosed) { _transaction?.Commit(); _transactionClosed = true; } }
public Task <int> SaveAsync() { var count = _dbContext.SaveChangesAsync(); _transaction?.Commit(); _transaction?.Dispose(); _transaction = null; return(count); }
public virtual void CleanUp() { if (RollBack) { _transaction?.Rollback(); } else { _transaction?.Commit(); } }
public async Task CompletedAsync() { if (_readOnly) { return; } _dataModelContext.ChangeTracker.DetectChanges(); await _dataModelContext.SaveChangesAsync(); _transaction?.Commit(); }
public void CommitTransaction() { try { _transaction?.Commit(); } catch { _transaction?.Rollback(); throw; } }
public void EndTransaction() { try { _transaction?.Commit(); } catch (Exception exc) { _transaction.Rollback(); throw exc; } }
public void Commit() { try { _context.SaveChanges(); _transaction?.Commit(); } catch (Exception e) { _transaction?.Rollback(); throw e; } }
public void Commit() { try { _context.SaveChanges(); _transaction?.Commit(); } catch { _transaction?.Rollback(); CleanUpTransaction(); throw; } }
public async Task CommitTransactionAsync() { try { await SaveChangesAsync().ConfigureAwait(false); _currentTransaction?.Commit(); } catch (Exception) { RollbackTransaction(); } finally { if (_currentTransaction != null) { _currentTransaction.Dispose(); _currentTransaction = null; } } }
public async Task CommitTransactionAsync() { try { await SaveChangesAsync().ConfigureAwait(false); DbContextTransaction?.Commit(); } catch { RollbackTransaction(); throw; } finally { if (DbContextTransaction != null) { DbContextTransaction.Dispose(); DbContextTransaction = null; } } }
public async Task CommitTransactionAsync() { try { await SaveChangesAsync(); _currentTransaction?.Commit(); } catch { RollbackTransaction(); throw; } finally { if (_currentTransaction != null) { _currentTransaction.Dispose(); _currentTransaction = null; } } }
public async Task CommitAsync(Exception exception = null) { try { if (_dbTransaction != null && exception != null) { _dbTransaction.Rollback(); Debug.WriteLine($" Rollback with Skip Transaction {_dbContext.Identifier}"); return; } await _dbContext.SaveChangesAsync().ConfigureAwait(false); Debug.WriteLine($" Commit Transaction {_dbContext.Identifier}"); _dbTransaction?.Commit(); } catch (Exception) { if (_dbTransaction?.UnderlyingTransaction.Connection != null) { _dbTransaction?.Rollback(); Debug.WriteLine($" Rollback Transaction {_dbContext.Identifier}"); } throw; } finally { if (_dbTransaction != null) { _dbTransaction.Dispose(); _dbTransaction = null; Debug.WriteLine($" Dispose Transaction {_dbContext.Identifier}"); } } }
static void Main(string[] args) { using (var db = new TrabajosConexion()) { db.Database.Log = Console.WriteLine; using (DbContextTransaction transaction = db.Database.BeginTransaction()) { try { //codigo Trabajos trabajo1 = new Trabajos { Titulo = "trabajo 1, continua en trabajo 2", Ubicacion = "Ciudad de méxico", Salario = 1870, Descripcion = "este trabajo se ingresa en primer lugar", TipoContratoId = 2, CategoriaTrabajoId = 12, FechaRegistro = DateTime.Now, FechaModificacion = DateTime.Now, Estado = true }; db.Entry(trabajo1).State = EntityState.Added; db.SaveChanges(); Trabajos trabajo2 = new Trabajos { Titulo = "trabajo 2, continua el trabajo 3", Ubicacion = "Ciudad de méxico", Salario = 1870, Descripcion = "este trabajo se ingresa en segundo lugar.", TipoContratoId = 2, CategoriaTrabajoId = 12, FechaRegistro = DateTime.Now, FechaModificacion = DateTime.Now, Estado = true }; db.Entry(trabajo2).State = EntityState.Added; db.SaveChanges(); Trabajos trabajo3 = new Trabajos { Titulo = "trabajo 3, finaliza el proceso", Ubicacion = "Ciudad de méxico", Salario = 1870, Descripcion = "este trabajo se ingresa en tercer lugar.", TipoContratoId = 2, CategoriaTrabajoId = 12, FechaRegistro = DateTime.Now, FechaModificacion = DateTime.Now, Estado = true }; db.Entry(trabajo3).State = EntityState.Added; db.SaveChanges(); transaction.Commit(); } catch (Exception ex) { transaction.Rollback(); Console.WriteLine(ex.Message); } } } Console.ReadKey(); }
/// <summary> /// 事务操作 /// </summary> static void Transaction() { #region 显示事务 //隐形事务 using (MasDBContext db = new MasDBContext()) { //db.Database.Connection.Open();//打开数据库连接 using (DbContextTransaction tran = db.Database.BeginTransaction()) { try { Donator article = new Donator() { Name = "陈志康", Amount = 50, DonateDate = new DateTime(2016, 4, 7) }; db.Donators.Add(article); db.SaveChanges(); article = new Donator() { Name = "陈志康", Amount = 50, DonateDate = new DateTime(2016, 4, 7) }; db.Donators.Add(article); db.SaveChanges(); //提交事务 tran.Commit(); } catch (Exception ex) { //回滚事务 tran.Rollback(); throw ex; } } } #endregion #region 分布式事务 (显示事务) //分布式事务 (显示事务) using (TransactionScope tran = new TransactionScope()) { #region 新增一 using (MasDBContext db = new MasDBContext()) { try { Donator article = new Donator() { Name = "陈志康", Amount = 50, DonateDate = new DateTime(2016, 4, 7) }; db.Donators.Add(article); db.SaveChanges(); article = new Donator() { Name = "陈志康", Amount = 50, DonateDate = new DateTime(2016, 4, 7) }; db.Donators.Add(article); db.SaveChanges(); } catch (Exception ex) { throw ex; } } #endregion //其他DBContext #region 新增二 using (MasDBContext db = new MasDBContext()) { try { Donator article = new Donator() { Name = "陈志康", Amount = 50, DonateDate = new DateTime(2016, 4, 7) }; db.Donators.Add(article); db.SaveChanges(); article = new Donator() { Name = "陈志康", Amount = 50, DonateDate = new DateTime(2016, 4, 7) }; db.Donators.Add(article); db.SaveChanges(); } catch (Exception ex) { throw ex; } } #endregion //提交事务 //tran.Complete(); } #endregion }
public void Commit() { transaction.Commit(); }
/// <summary> /// /// </summary> /// <param name="ids"></param> /// <param name="userID"></param> /// <param name="checkPermission"></param> /// <returns></returns> public CoreResult Delete(int[] ids, int?userID = null, bool checkPermission = false) { try { bool flag = false; if (userID == null && checkPermission) { return(new CoreResult { StatusCode = CoreStatusCode.Failed, Message = "\"UserID\" không được phép để trống." }); } else { if (checkPermission) { var per = this.GetPermission(userID.Value, ActionType.Delete); if (per.StatusCode == CoreStatusCode.OK) { ////action flag = true; } else { return(per); } } else { ////action flag = true; } } if (flag) { CoreResult resultReturn = new CoreResult(); using (DbContextTransaction dbTransaction = this.context.Database.BeginTransaction()) { foreach (int id in ids) { var doituongbenhnhan = this.GetByID(id); if (doituongbenhnhan != null) { doituongbenhnhan.deleted = true; this.context.Entry <patientsObject>(doituongbenhnhan).State = EntityState.Modified; } } try { this.context.SaveChanges(); dbTransaction.Commit(); resultReturn.StatusCode = CoreStatusCode.OK; resultReturn.Message = this.GetMessageByCoreStatusCode(CoreStatusCode.OK, ActionType.Delete); } catch (Exception ex) { dbTransaction.Rollback(); resultReturn.StatusCode = CoreStatusCode.Exception; resultReturn.Message = this.GetMessageByCoreStatusCode(CoreStatusCode.Exception, ActionType.Delete, ex); } } if (resultReturn.StatusCode == CoreStatusCode.OK && this.GetUseCache()) { this.RefreshCache(); } return(resultReturn); } else { return(new CoreResult { StatusCode = CoreStatusCode.DontHavePermission, Message = this.GetMessageByCoreStatusCode(CoreStatusCode.DontHavePermission, ActionType.Delete) }); } } catch (Exception ex) { return(new CoreResult { StatusCode = CoreStatusCode.Exception, Message = this.GetMessageByCoreStatusCode(CoreStatusCode.Exception, ActionType.Delete, ex) }); } }
/// <summary> /// /// </summary> /// <param name="_permissions"></param> /// <param name="useTransaction"></param> /// <returns></returns> public CoreResultRange <CoreResult> InsertOrUpdate(IEnumerable <Permission> _permissions, bool useTransaction = true, int?userId = default(int?), bool checkPermission = false) { try { #region Kiểm tra quyền var per = this.CheckPermission(userId, checkPermission, ActionType.Edit); if (!per.Item1) { return(new CoreResultRange <CoreResult> { StatusCode = per.Item2.StatusCode, Data = per.Item2.Data, Message = per.Item2.Message }); } #endregion IEnumerable <Permission> _updates = _permissions.Where(p => p.PermissionsID > 0); IEnumerable <Permission> _inserts = _permissions.Where(p => p.PermissionsID == 0); if (useTransaction) { using (DbContextTransaction dbTransaction = this.context.Database.BeginTransaction()) { //insert foreach (Permission permission in _inserts) { permission.Approved = false; this.context.Permissions.Add(permission); } //update foreach (Permission permission in _updates) { Permission atach = this.GetByID(permission.PermissionsID); if (atach != null) { atach.Views = permission.Views; atach.New = permission.New; atach.Edit = permission.Edit; atach.Deleted = permission.Deleted; atach.Prints = permission.Prints; this.context.Entry <Permission>(atach).State = EntityState.Modified; } } try { this.context.SaveChanges(); dbTransaction.Commit(); return(new CoreResultRange <CoreResult> { StatusCode = CoreStatusCode.OK, Data = _permissions, Message = this.GetMessageByCoreStatusCode(CoreStatusCode.OK, ActionType.Edit) }); } catch (Exception ex) { dbTransaction.Rollback(); return(new CoreResultRange <CoreResult> { StatusCode = CoreStatusCode.Exception, Data = _permissions, Message = this.GetMessageByCoreStatusCode(CoreStatusCode.Exception, ActionType.Edit, ex) }); } } } else { int sum = _permissions.Count(); var resultUpdate = this.UpdateRange(_updates); var resultInsert = this.InsertRange(_inserts); int _success = 0; List <CoreResult> _rSuccess = new List <CoreResult>(); List <CoreResult> _rError = new List <CoreResult>(); if (resultInsert.StatusCode == CoreStatusCode.OK) { if (resultInsert.Success != null) { _rSuccess.AddRange(resultInsert.Success.ToList()); } if (resultInsert.Error != null) { _rError.AddRange(resultInsert.Error.ToList()); } } else if (resultInsert.StatusCode == CoreStatusCode.Failed) { if (resultInsert.Error != null) { _rError.AddRange(resultInsert.Error.ToList()); } } if (resultUpdate.StatusCode == CoreStatusCode.OK) { if (resultUpdate.Success != null) { _rSuccess.AddRange(resultUpdate.Success.ToList()); } if (resultUpdate.Error != null) { _rError.AddRange(resultUpdate.Error.ToList()); } } else if (resultUpdate.StatusCode == CoreStatusCode.Failed) { if (resultUpdate.Error != null) { _rError.AddRange(resultUpdate.Error.ToList()); } } return(new CoreResultRange <CoreResult> { StatusCode = _success == 0 ? CoreStatusCode.OK : CoreStatusCode.Failed, Message = string.Format("Cập nhật thành công {0}/{1} mục", _rSuccess.Count, sum), Success = _rSuccess, Error = _rError }); } } catch (Exception ex) { return(new CoreResultRange <CoreResult> { StatusCode = CoreStatusCode.Exception, Data = _permissions, Message = this.GetMessageByCoreStatusCode(CoreStatusCode.Exception, ActionType.Edit, ex) }); } }
/// <summary> /// 販売データの内容に合わせてデータを更新する /// </summary> /// <param name="data">更新用データ</param> /// <returns>処理結果ステータスコード</returns> public HttpStatusCode SetSalesView(SalesViewApiModel data) { try { if (data == null) { WriteAppLog(this.ToString() + ".SetSalesView", ErrorMessage.CParamError); return(HttpStatusCode.BadRequest); } if (data.Product == null || data.Product.Id <= 0) { WriteAppLog(this.ToString() + ".SetSalesView", ErrorMessage.CKeyError); return(HttpStatusCode.BadRequest); } int product_id = dbContext.ProductModels.Where(pd => pd.Id == data.Product.Id).Select(pd => pd.Id).SingleOrDefault(); if (product_id == 0) { WriteAppLog(this.ToString() + ".SetSalesView", ErrorMessage.CProductError); return(HttpStatusCode.BadRequest); } int office_id = dbContext.OfficeModels.Where(o => o.Code == "**").Select(o => o.Id).SingleOrDefault(); if (office_id == 0) { WriteAppLog(this.ToString() + ".SetSalesView", ErrorMessage.COfficeIdError); return(HttpStatusCode.InternalServerError); } // 最小日付と最大日付 DateTime MinDate = data.SalesList.Select(sl => sl.detail_date).Min(); DateTime MaxDate = data.SalesList.Select(sl => sl.detail_date).Max(); using (DbContextTransaction tx = dbContext.Database.BeginTransaction(System.Data.IsolationLevel.Serializable)) { foreach (var month in data.SalesList) { if (month.detail_date != MinDate) { // 販売予算を更新 SalesModel sales = dbContext.SalesModels.Where(sls => sls.ProductModelId == product_id) .Where(sls => sls.TargetDate == month.detail_date) .Where(sls => sls.OfficeModelId == office_id).SingleOrDefault(); if (sales != null) { // 削除データが表示される際に不整合を起こさないため if (sales.Deleted) { sales.Sales = 0; } sales.Plan = month.sales_plan; sales.Deleted = false; } else { if (month.sales_plan != 0) { sales = new SalesModel(); sales.ProductModelId = product_id; sales.TargetDate = month.detail_date; sales.Plan = month.sales_plan; sales.OfficeModelId = office_id; dbContext.SalesModels.Add(sales); } } dbContext.SaveChanges(); // 貿易 TradeModel trades = dbContext.TradeModels.Where(trd => trd.ProductModelId == product_id) .Where(trd => trd.TargetDate == month.detail_date).SingleOrDefault(); if (trades != null) { // 削除データが表示される際に不整合を起こさないため if (trades.Deleted) { trades.Order = 0; trades.Invoice = 0; trades.RemainingInvoice = 0; } trades.OrderPlan = month.order_plan; trades.InvoicePlan = month.invoice_plan; trades.AdjustmentInvoice = month.invoice_adjust; trades.Deleted = false; } else { trades = new TradeModel(); trades.ProductModelId = product_id; trades.TargetDate = month.detail_date; trades.OrderPlan = month.order_plan; trades.InvoicePlan = month.invoice_plan; trades.AdjustmentInvoice = month.invoice_adjust; dbContext.TradeModels.Add(trades); } dbContext.SaveChanges(); } } tx.Commit(); } // 再計算 dbContext.Database.ExecuteSqlCommand( "call _recalculation_invoicedata_id(@p0,@p1,@p2)", MinDate, DateTime.Now.Date, product_id); WriteAppLog(this.ToString() + ".SetSalesView", ErrorMessage.CCompleteSet.Replace("@product", product_id.ToString())); return(HttpStatusCode.OK); } catch (Exception ex) { WriteAppLog(this.ToString() + ".SetSalesView", ErrorMessage.CException + ex.Message); return(HttpStatusCode.InternalServerError); } }
public IHttpActionResult PutExpense(int id, ExpenseViewModel ExpenseViewModel) { string refId = ExpenseViewModel.Id.ToString(); EXPENSE expenseTable = new EXPENSE(); ExpenseModel _ExpeseModel = new ExpenseModel(); AccountTransictionTable AccountTable = new AccountTransictionTable(); AccountTable.TransictionDate = DateTime.Now; AccountTable.TransictionNumber = base64Guid; AccountTable.TransictionType = "Expence"; AccountTable.CreationTime = DateTime.Now.TimeOfDay; AccountTable.FK_CompanyId = ExpenseViewModel.comapny_id; AccountTable.FKPaymentTerm = 1; AccountTable.TransictionRefrenceId = ExpenseViewModel.Id.ToString(); AccountTable.AddedBy = ExpenseViewModel.user_id; using (DBEntities context = new DBEntities()) { using (DbContextTransaction transaction = context.Database.BeginTransaction(System.Data.IsolationLevel.ReadCommitted)) { try { List <AccountTransictionTable> List = new List <AccountTransictionTable>(); List = context.AccountTransictionTables.Where(t => t.TransictionRefrenceId == refId.ToString()).ToList(); context.AccountTransictionTables.RemoveRange(context.AccountTransictionTables.Where(F => F.TransictionRefrenceId == refId.ToString())); context.SaveChanges(); EXPENSE expense = new EXPENSE(); expense.REFERENCEno = ExpenseViewModel.REFERENCEno; expense.ACCOUNT_ID = ExpenseViewModel.ACCOUNT_ID; expense.Id = ExpenseViewModel.Id; expense.VENDOR_ID = ExpenseViewModel.VENDOR_ID; expense.notes = ExpenseViewModel.notes; expense.user_id = ExpenseViewModel.user_id; expense.SUBTOTAL = ExpenseViewModel.SUBTOTAL; expense.VAT_AMOUNT = ExpenseViewModel.VAT_AMOUNT; expense.GRAND_TOTAL = ExpenseViewModel.GRAND_TOTAL; expense.AddedDate = ExpenseViewModel.AddedDate; expense.comapny_id = ExpenseViewModel.comapny_id; expense.Vat6 = ExpenseViewModel.Vat6; expense.Vat21 = ExpenseViewModel.Vat21; context.Entry(expense).State = EntityState.Modified; context.SaveChanges(); if (ExpenseViewModel.ExpensenDetailList != null) { foreach (ExpenseDetail item in ExpenseViewModel.ExpensenDetailList) { ExpenseDetail expenseDetailModel = new ExpenseDetail(); expenseDetailModel.expense_id = ExpenseViewModel.Id; expenseDetailModel.EXPENSE_ACCOUNT_ID = item.EXPENSE_ACCOUNT_ID; expenseDetailModel.DESCRIPTION = item.DESCRIPTION; expenseDetailModel.AMOUNT = item.AMOUNT; expenseDetailModel.TAX_PERCENT = item.TAX_PERCENT; expenseDetailModel.TAX_AMOUNT = item.TAX_AMOUNT; expenseDetailModel.SUBTOTAL = item.SUBTOTAL; expenseDetailModel.Id = item.Id; expenseDetailModel.user_id = ExpenseViewModel.user_id; expenseDetailModel.comapny_id = ExpenseViewModel.comapny_id; AccountTable.Cr = 0.00; AccountTable.Dr = item.AMOUNT; AccountTable.FK_AccountID = item.EXPENSE_ACCOUNT_ID; context.AccountTransictionTables.Add(AccountTable); context.SaveChanges(); if (item.Id == 0) { context.ExpenseDetails.Add(expenseDetailModel); context.SaveChanges(); } else { context.Entry(expenseDetailModel).State = EntityState.Modified; context.SaveChanges(); } } } //Accounts Petty Cash Transaction int Accountpayble = AccountIdByName("Petty Cash", (int)ExpenseViewModel.comapny_id); if (Accountpayble != 0) { AccountTable.Dr = 0.00; AccountTable.Cr = ExpenseViewModel.GRAND_TOTAL; AccountTable.FK_AccountID = Accountpayble; context.AccountTransictionTables.Add(AccountTable); context.SaveChanges(); } // Cost Of Goods Transaction int CostOfGood = AccountIdByName("Input VAT", (int)ExpenseViewModel.comapny_id); if (CostOfGood != 0) { AccountTable.Cr = 0.00; AccountTable.Dr = ExpenseViewModel.Vat21 + ExpenseViewModel.Vat6;; AccountTable.FK_AccountID = CostOfGood; context.AccountTransictionTables.Add(AccountTable); context.SaveChanges(); } _ExpeseModel.Id = expenseTable.Id; transaction.Commit(); return(Ok(_ExpeseModel)); } catch (Exception ex) { transaction.Commit(); return(BadRequest()); } } } //if (!ModelState.IsValid) //{ // return BadRequest(ModelState); //} //if (id != ExpenseTable.Id) //{ // return BadRequest(); //} //db.Entry(ExpenseTable).State = EntityState.Modified; //try //{ // db.SaveChanges(); // return Ok(ExpenseTable); //} //catch (Exception ex) //{ // BadRequest(); // throw; //} }
public async Task <bool> Reset() { using (DbContextTransaction transaction = db.Database.BeginTransaction()) { try { var allcontacts = await db.Contacts.DefaultIfEmpty().ToListAsync(); var allEmailLists = await db.EmailLists.DefaultIfEmpty().ToListAsync(); if (allcontacts[0] != null) { db.Contacts.RemoveRange(allcontacts); } if (allEmailLists[0] != null) { db.EmailLists.RemoveRange(allEmailLists); } List <EmailList> TeamA = new List <EmailList>() { new EmailList() { EmailListName = "Team A" } }; List <EmailList> BetConstract = new List <EmailList>() { new EmailList() { EmailListName = "BetConstruct" } }; List <EmailList> OtherPeople = new List <EmailList>() { new EmailList() { EmailListName = "Other team members" } }; List <Contact> startContacts = new List <Contact>() { new Contact() { FullName = "Vanik Hakobyan", CompanyName = "YSU", Country = "Armenia", Position = "Student", Email = "*****@*****.**", EmailLists = TeamA, GuID = Guid.NewGuid(), DateInserted = DateTime.Now }, new Contact() { FullName = "Khachatur Sukiasyan", CompanyName = "Microsoft", Country = "Armenia", Position = "Freelancer", Email = "*****@*****.**", EmailLists = TeamA, GuID = Guid.NewGuid(), DateInserted = DateTime.Now }, new Contact() { FullName = "Tsovinar Ghazaryan", CompanyName = "VTB Bank", Country = "Armenia", Position = "Credit Controller", Email = "*****@*****.**", EmailLists = TeamA, GuID = Guid.NewGuid(), DateInserted = DateTime.Now }, new Contact() { FullName = "Tatevik Begjanyan", CompanyName = "TB LLC", Country = "Armenia", Position = "Foreign Affairs Manager", Email = "*****@*****.**", EmailLists = TeamA, GuID = Guid.NewGuid(), DateInserted = DateTime.Now }, new Contact() { FullName = "Narine Boyakhchyan", CompanyName = "NB LLC", Country = "Armenia", Position = "Director", Email = "*****@*****.**", EmailLists = TeamA, GuID = Guid.NewGuid(), DateInserted = DateTime.Now }, new Contact() { FullName = "Zara Muradyan", CompanyName = "ZM LLC", Country = "Armenia", Position = "Director", Email = "*****@*****.**", EmailLists = TeamA, GuID = Guid.NewGuid(), DateInserted = DateTime.Now }, new Contact() { FullName = "Tigran Vardanyan", CompanyName = "Candle", Country = "Switzerland", Position = "Theoretician", Email = "*****@*****.**", EmailLists = OtherPeople, GuID = Guid.NewGuid(), DateInserted = DateTime.Now }, new Contact() { FullName = "Aram Jamkotchian", CompanyName = "MIC", Country = "Spain", Position = "Lead", Email = "*****@*****.**", EmailLists = OtherPeople, GuID = Guid.NewGuid(), DateInserted = DateTime.Now }, new Contact() { FullName = "Lusine Hovsepyan", CompanyName = "SCDM GmbH", Country = "Armenia", Position = "Financial Analyst", Email = "*****@*****.**", EmailLists = OtherPeople, GuID = Guid.NewGuid(), DateInserted = DateTime.Now }, new Contact() { FullName = "Gayane Khachatryan", CompanyName = "Khachatryan LLC", Country = "Armenia", Position = "Owner", Email = "*****@*****.**", EmailLists = OtherPeople, GuID = Guid.NewGuid(), DateInserted = DateTime.Now }, new Contact() { FullName = "Narek Yegoryan", CompanyName = "NPUA", Country = "Armenia", Position = "Student", Email = "*****@*****.**", EmailLists = OtherPeople, GuID = Guid.NewGuid(), DateInserted = DateTime.Now }, new Contact() { FullName = "Lusine Khachatryan", CompanyName = "LK LLC", Country = "Armenia", Position = "Director", Email = "*****@*****.**", EmailLists = OtherPeople, GuID = Guid.NewGuid(), DateInserted = DateTime.Now }, new Contact() { FullName = "George Voyatzis", CompanyName = "BetConstruct", Country = "London - United Kingdom", Position = "Commercial Director", Email = "*****@*****.**", EmailLists = BetConstract, GuID = Guid.NewGuid(), DateInserted = DateTime.Now }, new Contact() { FullName = "Anna Poghosyan", CompanyName = "BetConstruct", Country = "Yerevan - Armenia", Position = "International Development Director", Email = "*****@*****.**", EmailLists = BetConstract, GuID = Guid.NewGuid(), DateInserted = DateTime.Now }, new Contact() { FullName = "Anna Shahbazyan", CompanyName = "BetConstruct", Country = "Montevideo - Uruguay", Position = "Regional Director", Email = "*****@*****.**", EmailLists = BetConstract, GuID = Guid.NewGuid(), DateInserted = DateTime.Now }, new Contact() { FullName = "Samvel Nersisyan", CompanyName = "BetConstruct", Country = "Yerevan - Armenia", Position = "Head of Business Development", Email = "*****@*****.**", EmailLists = BetConstract, GuID = Guid.NewGuid(), DateInserted = DateTime.Now }, new Contact() { FullName = "Zorair Asadour", CompanyName = "BetConstruct", Country = "Cape Town - South Africa", Position = "Regional Director", Email = "*****@*****.**", EmailLists = BetConstract, GuID = Guid.NewGuid(), DateInserted = DateTime.Now }, new Contact() { FullName = "Stephan Mamikonjan", CompanyName = "BetConstruct", Country = "Vienna - Austria", Position = "Regional Director", Email = "*****@*****.**", EmailLists = BetConstract, GuID = Guid.NewGuid(), DateInserted = DateTime.Now } }; db.Contacts.AddRange(startContacts); db.EmailLists.AddRange(BetConstract); db.EmailLists.AddRange(OtherPeople); await db.SaveChangesAsync(); transaction.Commit(); return(true); } catch { transaction.Rollback(); return(false); } } }
public void Commit() { context.SaveChanges(); transaction.Commit(); }
public int SaveInDbTransaction(IsolationLevel isolationLevel = IsolationLevel.ReadCommitted) { DbContextTransaction transaction = null; try { transaction = _context.Database.BeginTransaction(IsolationLevel.ReadCommitted); using (transaction) { #region Handling auditing var modifiedEntries = _context.ChangeTracker.Entries() .Where(x => x.Entity is IAuditableEntity && (x.State == EntityState.Added || x.State == EntityState.Modified)); foreach (var entry in modifiedEntries) { var entity = entry.Entity as IAuditableEntity; if (entity != null) { var identityName = Thread.CurrentPrincipal.Identity.Name; var now = DateTime.UtcNow; if (entry.State == EntityState.Added) { entity.CreatedBy = identityName; entity.Created = now; } else { _context.Entry(entity).Property(x => x.CreatedBy).IsModified = false; _context.Entry(entity).Property(x => x.Created).IsModified = false; } entity.ModifiedBy = identityName; entity.Modified = now; } } #endregion var affectedRows = _context.SaveChanges(); transaction.Commit(); return(affectedRows); } } catch (DbEntityValidationException dbEx) { foreach (var validationError in dbEx.EntityValidationErrors.SelectMany( validationErrors => validationErrors.ValidationErrors)) { ErrorMessage += $"Property: {validationError.PropertyName} Error: {validationError.ErrorMessage}" + Environment.NewLine; } transaction?.Rollback(); throw new Exception(ErrorMessage, dbEx); } catch (Exception exception) { ErrorMessage = exception.Message; transaction?.Rollback(); throw new Exception(ErrorMessage, exception); } }
private bool SaveOfferta(Payment payment) { OffertaModel offerta = Session["PayPalOfferta"] as OffertaModel; using (DatabaseContext db = new DatabaseContext()) { db.Database.Connection.Open(); // AGGIUNGERE TRANSAZIONE NELLA TABELLA DEI LOG LOG_PAGAMENTO log = new LOG_PAGAMENTO(); OFFERTA model = db.OFFERTA.Include(m => m.PERSONA) .Include(m => m.ANNUNCIO.ANNUNCIO_TIPO_SCAMBIO) .SingleOrDefault(m => m.ID == offerta.ID); log.ID_ANNUNCIO = model.ID_ANNUNCIO; log.ID_COMPRATORE = model.ID_PERSONA; log.ID_PAGAMENTO = model.ID.ToString(); log.ISTITUTO_PAGAMENTO = "PAYPAL"; log.NOME_ANNUNCIO = "Offerta per l'annuncio " + model.ANNUNCIO.NOME; log.DATA_INSERIMENTO = DateTime.Now; db.LOG_PAGAMENTO.Add(log); db.SaveChanges(); // cambia stato spedizione in pagata OFFERTA_SPEDIZIONE spedizione = model.OFFERTA_SPEDIZIONE.FirstOrDefault(); spedizione.DATA_MODIFICA = DateTime.Now; spedizione.STATO = (int)StatoSpedizione.PAGATA; db.OFFERTA_SPEDIZIONE.Attach(spedizione); db.Entry(spedizione).State = EntityState.Modified; db.SaveChanges(); int idPayPal = SavePayPal(db, payment); using (DbContextTransaction transaction = db.Database.BeginTransaction()) { try { var utente = (Session["utente"] as PersonaModel); string messaggio = string.Empty; // ripopolo classe offerta per calcoli nella funzione ACCETTA offerta.OffertaOriginale = model; offerta.ANNUNCIO.ANNUNCIO_TIPO_SCAMBIO = db.ANNUNCIO_TIPO_SCAMBIO .Include(m => m.ANNUNCIO_TIPO_SCAMBIO_SPEDIZIONE) .Where(m => m.ID_ANNUNCIO == offerta.ID_ANNUNCIO).ToList(); offerta.AnnuncioModel.ANNUNCIO_TIPO_SCAMBIO = offerta.ANNUNCIO.ANNUNCIO_TIPO_SCAMBIO; //if (offerta.Accetta(db, utente.Persona, utente.Credito, ref messaggio)) => non passa compratore nell'offerta if (offerta.Accetta(db, utente.Persona, idPayPal, ref messaggio)) { transaction.Commit(); Models.ViewModels.Email.PagamentoOffertaViewModel offertaAccettata = new Models.ViewModels.Email.PagamentoOffertaViewModel(); offertaAccettata.NominativoDestinatario = offerta.PERSONA.NOME + " " + offerta.PERSONA.COGNOME; offertaAccettata.NomeAnnuncio = offerta.ANNUNCIO.NOME; offertaAccettata.Moneta = offerta.PUNTI; offertaAccettata.SoldiSpedizione = offerta.SOLDI; offertaAccettata.Baratti = offerta.OFFERTA_BARATTO.Select(m => m.ANNUNCIO.NOME).ToList(); this.SendNotifica(utente.Persona, offerta.PERSONA, TipoNotifica.OffertaAccettata, ControllerContext, "offertaAccettata", offertaAccettata); //System.Web.Routing.RouteValueDictionary data = new System.Web.Routing.RouteValueDictionary(new { token = offerta.ID }); _UrlFinePagamento = Url.Action("OfferteRicevute", "Vendite", null, this.Request.Url.Scheme, this.Request.Url.Host); //return (db.SaveChanges() > 0); return(true); } } catch (Exception ex) { transaction.Rollback(); LoggatoreModel.Errore(ex); throw ex; } } } return(false); }
/// <summary> /// 提交一个事务 /// </summary> /// <param name="transaction"></param> public static void Commit(DbContextTransaction transaction) { transaction.Commit(); }
/// <summary> /// Persists all updates to the data source and resets change tracking in the object context. /// </summary> /// <returns>The number of objects in an System.Data.Entity.EntityState.Added, System.Data.Entity.EntityState.Modified, or System.Data.Entity.EntityState.Deleted state when System.Data.Objects.ObjectContext.SaveChanges() was called.</returns> public override int SaveChanges() { var cancel = false; OnBeforeSaveChanges(ref cancel); if (cancel) { return(0); } //This must be called to truly see all Added/Updated Entities in the ObjectStateManager!!! //Items added to context work fine, but children added to parent objects do not i.e. 'ParentObject.ChildItems.Add(newChild)' this.ChangeTracker.Entries().Any(); //Get the added list var addedList = this.ObjectContext.ObjectStateManager.GetObjectStateEntries(System.Data.Entity.EntityState.Added); var markedTime = System.DateTime.Now; //Process added list foreach (var item in addedList) { var entity = item.Entity as IAuditable; if (entity != null) { var audit = entity as IAuditableSet; if (audit != null && entity.IsModifyAuditImplemented && entity.ModifiedBy != this.ContextStartup.Modifer) { if (audit != null) { audit.ResetCreatedBy(this.ContextStartup.Modifer); } if (audit != null) { audit.ResetModifiedBy(this.ContextStartup.Modifer); } } if (audit != null) { audit.CreatedDate = markedTime; audit.ModifiedDate = markedTime; } } } this.OnBeforeSaveAddedEntity(new EventArguments.EntityListEventArgs { List = addedList }); //Process modified list var modifiedList = this.ObjectContext.ObjectStateManager.GetObjectStateEntries(System.Data.Entity.EntityState.Modified); foreach (var item in modifiedList) { var entity = item.Entity as IAuditable; if (entity != null) { var audit = entity as IAuditableSet; if (entity.IsModifyAuditImplemented && entity.ModifiedBy != this.ContextStartup.Modifer) { if (audit != null) { audit.ResetModifiedBy(this.ContextStartup.Modifer); } } audit.ModifiedDate = markedTime; } } this.OnBeforeSaveModifiedEntity(new EventArguments.EntityListEventArgs { List = modifiedList }); var retval = 0; DbContextTransaction customTrans = null; try { _paramList.Clear(); if (base.Database.CurrentTransaction == null) { customTrans = base.Database.BeginTransaction(); } retval += QueryPreCache.ExecuteDeletes(this); retval += base.SaveChanges(); retval += QueryPreCache.ExecuteUpdates(this); if (customTrans != null) { customTrans.Commit(); } } catch (System.Data.Entity.Validation.DbEntityValidationException ex) { var sb = new System.Text.StringBuilder(); foreach (var error in ex.EntityValidationErrors) { foreach (var validationError in error.ValidationErrors) { sb.AppendLine(validationError.PropertyName + ": " + validationError.ErrorMessage); } } throw new System.Data.Entity.Validation.DbEntityValidationException(sb.ToString(), ex.EntityValidationErrors); } catch { throw; } finally { if (customTrans != null) { customTrans.Dispose(); } } this.OnAfterSaveAddedEntity(new EventArguments.EntityListEventArgs { List = addedList }); this.OnAfterSaveModifiedEntity(new EventArguments.EntityListEventArgs { List = modifiedList }); OnAfterSaveChanges(); return(retval); }
// public Activos Save(Activos activo) // { // int retorno = 0; // Activos oActivo = null; // try // { // using (MyContext ctx = new MyContext()) // { // ctx.Configuration.LazyLoadingEnabled = false; // oActivo = GetActivoByID(activo.ActivoID); // if (oActivo == null) // { // ctx.Activos.Add(activo); // } // else // { // ctx.Entry(activo).State = EntityState.Modified; // } // retorno = ctx.SaveChanges(); //#if !DEBUG // // Error por exception // int x = 0; // x = 25 / x; // // Error por Entity Framework // // Forzar un error por duplicidad // // bodega.IdBodega = 1; // // ctx.Bodega.Add(bodega); // // retorno = ctx.SaveChanges(); //#endif // } // if (retorno >= 0) // oActivo = GetActivoByID(activo.ActivoID); // return oActivo; // } // catch (DbUpdateException dbEx) // { // string mensaje = ""; // Log.Error(dbEx, System.Reflection.MethodBase.GetCurrentMethod(), ref mensaje); // throw new Exception(mensaje); // } // //Checking any Entity Validation Exception // catch (DbEntityValidationException e) // { // foreach (var eve in e.EntityValidationErrors) // { // Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", // eve.Entry.Entity.GetType().Name, eve.Entry.State); // foreach (var ve in eve.ValidationErrors) // { // Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", // ve.PropertyName, ve.ErrorMessage); // } // } // throw; // } // catch (Exception ex) // { // string mensaje = ""; // Log.Error(ex, System.Reflection.MethodBase.GetCurrentMethod(), ref mensaje); // throw; // } // } //SaveTransaccion is in charge of save "Activo" and "Depreciacion" //Based on "FechaCompra" the value of "ValorActual" is received //update from the previous method ServiceActivo >> "SaveTransaccion" public Activos SaveTransaccion(Activos activo) { int retorno = 0; Activos oActivo = null; using (MyContext ctx = new MyContext()) { //Transaction Begin statement using (DbContextTransaction transaccion = ctx.Database.BeginTransaction()) { int indicador = 0; // variable creada [ara saber cuando un activo se esta editando try { ctx.Configuration.LazyLoadingEnabled = false; oActivo = GetActivoByID(activo.ActivoID); if (oActivo == null) { ctx.Activos.Add(activo); } else { ctx.Entry(activo).State = EntityState.Modified; indicador = 1; } retorno = ctx.SaveChanges(); if ((retorno >= 0) && (indicador == 0)) { //oActivo = GetActivoByID(activo.ActivoID); //Guardamos la depreciacion basados en el nuevo ID y en el calculo realizado previamente //Necesito cambiar Valor a decimal en la base de datos Depreciacion oDepreciacion = new Depreciacion(); oDepreciacion.Valor = activo.ValorActual.ToString(); oDepreciacion.Fecha = DateTime.Now; oDepreciacion.Activo = activo.ActivoID; ctx.Depreciacion.Add(oDepreciacion); retorno = ctx.SaveChanges(); } if (retorno >= 0)//Se insertan llena la tabla Activos y depreciacion en la DB { transaccion.Commit(); } return(oActivo); } catch (DbUpdateException dbEx) { transaccion.Rollback(); //Rollback si algo sale mal string mensaje = ""; Log.Error(dbEx, System.Reflection.MethodBase.GetCurrentMethod(), ref mensaje); throw new Exception(mensaje); } //Checking any Entity Validation Exception catch (DbEntityValidationException e) { transaccion.Rollback(); //Rollback si algo sale mal foreach (var eve in e.EntityValidationErrors) { Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); } } throw; } catch (Exception ex) { transaccion.Rollback(); //Rollback si algo sale mal string mensaje = ""; Log.Error(ex, System.Reflection.MethodBase.GetCurrentMethod(), ref mensaje); throw; } } } //docs.microsoft.com/en-us/dotnet/api/system.data.linq.table-1.insertonsubmit?view=netframework-4.8 //techfunda.com/howto/288/insert-record-using-transactions }
public void Commit() { _dbContextTransaction.Commit(); }