Doubt with Try Catch

0

I have the following code:

try
{
modelOn.pacienteOns.Add(Conversao.pacienteToOn(oObjeto));
oObjeto.online = 1;
modelOn.SaveChanges();
modelOff.SaveChanges();
}
catch (Exception i)
{
MessageBox.Show("----------------->>> " + i);
}

I need the system to execute the two commands modelOn.SaveChanges() and modelOff.SaveChanges() , if it does not execute one, it should not execute the other one.

My question is: Since I have included both of the codes within try , will either the two be executed or do I run one?

    
asked by anonymous 09.04.2017 / 16:23

2 answers

2

I got this code in DevMedia support:

var bancoOnTx = bancoOn.Database.BeginTransaction();
var bancoOffTx = bancoOff.Database.BeginTransaction();
try{
    //faz as transações
    bancoOn.SaveChanges(); 
    bancoOff.SaveChanges();
    bancoOnTx.Commit(); 
    bancoOffTx.Commit(); 
} 
catch (Exception e){ 
    bancoOnTx.Rollback();
    bancoOffTx.Rollback();
    MessageBox.Show(e);
}
    
16.04.2017 / 17:04
2

try catch can be seen as a crash protection to handle exception errors in a secure way. The program tries to execute what is in block try and if it encounters an exception error, it jumps to block catch . If there are no errors, skip the block catch .

What you want (executing a command conditionally) has nothing to do with this structure (which is protection against error and not conditional execution).

To do what you want, focus on the block and put the conditional inside it.

{
 modelOn.pacienteOns.Add(Conversao.pacienteToOn(oObjeto));
 oObjeto.online = 1;
 modelOn.SaveChanges();
 modelOff.SaveChanges();
}

As we do not know what methods return (if they return any value), I'll propose a code for you to use as an example:

{
 modelOn.pacienteOns.Add(Conversao.pacienteToOn(oObjeto));
 oObjeto.online = 1;
 if (modelOn.SaveChanges()) modelOff.SaveChanges();
}

In this code, I'm assuming that the method SaveChanges() of modelOn returns true if saved and false if not saved. In this way the SaveChanges() of modelOn method is only executed if the other has executed successfully.

    
09.04.2017 / 16:59