private bool VoteCandidate(User user, Candidate candidate, Voting voting) { using (var transaction = db.Database.BeginTransaction()) { var votingDetail = new VotingDetail { CandidateId = candidate.CandidateId, DateTime = DateTime.Now, UserId = user.UserId, VotingId = voting.VotingId, }; db.VotingDetails.Add(votingDetail); candidate.QuantityVotes++; db.Entry(candidate).State = EntityState.Modified; voting.QuantityVotes++; db.Entry(voting).State = EntityState.Modified; try { db.SaveChanges(); transaction.Commit(); return(true); } catch (Exception ex) { transaction.Rollback(); } } return(false); }
private bool VoteCandidate(User user, Candidate candidate, Voting voting) { //Debido que el voto se registrara en varias tablas, usaremos transacciones using (var transaction = db.Database.BeginTransaction()) { var votingDetail = new VotingDetail() { CandidateId = candidate.CandidateId, DateTime = DateTime.Now, UserId = user.UserId, VotingId = voting.VotingId }; //agregamos el el voting details db.VotingDetails.Add(votingDetail); //modificamos la cantidad de votos del candidato candidate.QuantityVotes++; db.Entry(candidate).State = EntityState.Modified; //modificamos la cantidad de votos del voting voting.QuantityVotes++; db.Entry(voting).State = EntityState.Modified; try { //guardamos los registros db.SaveChanges(); //si no hay ningun error se confirma la transacción transaction.Commit(); return(true); } catch (Exception) { //deshacemos los registros modificados antes de que haya ocurrido el error transaction.Rollback(); } } return(false); }