The try
catch
can be seen as a protection against 'crash' to handle exception errors in a secure way. The program tries to execute what is in the block try
and if you find an exception error, jump to the block catch
. No mistakes, skip the block catch
.
What you want (to execute a command conditionally) has nothing to do with this structure (which is protection against error and not conditional execution).
So you can do what you want, focus on the block and get your parole into it.
{
modelOn.pacienteOns.Add(Conversao.pacienteToOn(oObjeto));
oObjeto.online = 1;
modelOn.SaveChanges();
modelOff.SaveChanges();
}
Since we do not know what the methods return (if they return any value), I will propose a code to use example:
{
modelOn.pacienteOns.Add(Conversao.pacienteToOn(oObjeto));
oObjeto.online = 1;
if (modelOn.SaveChanges()) modelOff.SaveChanges();
}
In this code, I’m assuming the method SaveChanges()
of modelOn
returns true
was saved and false
if not saved. Thus the method SaveChanges()
of modelOn
is only executed if the other has successfully executed.
If any of the lines above them burst an exception, you run the risk of neither of the two being executed. Exception interrupts execution and jumps straight pro catch.
– user28595
That’s what I want. Or both or none. You confirm to me if that’s how it is anyway?
– Italo Rodrigo
The reasoning is the same, and with this code there is no way to guarantee it. If
modelOff.SaveChanges();
launch exception for some reason, Try code is stopped, butmodelOn.SaveChanges();
will have already executed.– user28595
Is there another way to do? to run all or none?
– Italo Rodrigo