When I post and I receive the model, this model contains errors. I delete these errors in the following way.
if (!ModelState.IsValid)
{
int pos = 0;
while (pos < ModelState.Keys.Count())
{
if (ModelState[ModelState.Keys.ElementAt(pos)].Errors.Any())
{
ModelState[ModelState.Keys.ElementAt(pos)].Errors.Clear();
}
pos++;
}
}
bool mod = ModelState.IsValid;
when I executed the process of the while in the bool I have a true, that is, my model is valid. After this process I keep the model in the following way.
reg x = _context.register.Create();
x = _context.register.Add(data);
try
{
_context.SaveChanges();
}
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;
}
I do not understand that having cleaned the ModelState of errors whenever I keep entering the catch and I am shown the error fields of my model that I had theoretically cleaned previously. why?
Because it exists two steps when validating your model.
The first step is done by ASP.Net MVC Validation which validates before you use it in your action method. Actually in your code you just clean the error list detected by ASP.Net MVC but you haven't set correct values to the properties of your model impacted by the errors.
After this first step of validation, comes Entity Framework Validation which is executed when saving your entities to your database by calling SaveChanges
. EF also use the same way as ASP.Net MVC by using data annnotations and it also uses the configuration of your model to validate your entity. Like I already said, you just cleared the error message but not settings the correct values so with EF you'll end up having the same errors.
Cleaning the errors messages in your action method doesn't help so much except after that you set the correct values for each property concerned by the errors.
Anyway if you want to disabled EF validations you can do it by settings this configuration in your DbContext
constructor:
this.Configuration.ValidateOnSaveEnabled = false;
This is not recommended because you may save into your database incorrect data. You may also get exception from your database e.g. when your database has a required column but you send a null
value from the property that is mapped to that column.