I have a user control with some fields like a textBox called textBoxNombre
I have some validation annotations like:
[Required(ErrorMessage="Debe escribir el Nombre")]
public String Nombre { get; set; }
This is the simplified code for a button (called buttonAgregar) used to add a new Cliente (Customer):
private void buttonAgregar_Click(object sender, RoutedEventArgs e)
{
var cliente = new Cliente
{
Nombre = textBoxNombre.Text,
Apellido1 = textBoxPrimerApellido.Text,
Apellido2 = textBoxSegundoApellido.Text,
};
db.Clientes.Add(cliente);
try
{
db.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException exc)
{
String mensaje = "";
foreach (var validationErrors in exc.EntityValidationErrors)
foreach (var validationError in validationErrors.ValidationErrors)
mensaje += validationError.ErrorMessage + "\n";
MessageBox.Show(mensaje, "Se han encontrado errores", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
If I left textBoxNombre empty then the exception is triggered and the message box is shown.
Then I type some text in textBoxNombre but when I click on buttonAgregar again the exception is triggered and the message box is shown again with the same error message.
The buttonAgregar_Click() method don’t get the new value in textBoxNombre.
How can I solve this?
That is because the previously created
Clienteinstance is still tracked by the context and when you callSaveChangesthat entity also get validated. Hence you get the validation exception.Detach the entity if you get any validation errors. You may also use new instance of the context each time the button is clicked.