-1

I have model class which consist of 3 required field. I am submitting MVC form with only 2 required fields and keeping one field blank (PhoneNumber).

public class User
{
    [Required]
    public String UserName { get; set; }
    [Required]
    public string Email { get; set; }
    [Required]
    public string PhoneNumber { get; set;}
}

On Action result, I got ModelState Invalid that is true. I then remove that invalid property from ModelState using ModelState.Remove("PhoneNumber"); I then again check ModelState becomes true after that.

but while saving model, it is throwing entity validation error because of blank field (PhoneNumber) although I removed invalid property from ModelState. How to skip entity validation error in such scenario and let save the model in database.

SSD
  • 1,041
  • 3
  • 19
  • 39
  • 1
    EF prevents save null data to the non-nullable field on database. – Sina Riani Jul 13 '21 at 09:19
  • Pls post the code you used to save updated record. – Serge Jul 13 '21 at 11:07
  • 1
    `ModelState.Remove` will disable the server-side validation but the null check is still there in your database which is causing the issue. It is always better to have different models for your database and front-end views and map between the two using something like [Automapper](https://docs.automapper.org/en/stable/Getting-started.html) – prinkpan Jul 13 '21 at 11:14
  • If you didn't want to submit the `PhoneNumber` field, then remove `required` validation from the model and set it as `NULL` in the SQL table. –  Jul 14 '21 at 05:22

1 Answers1

0

Your model works against SQL. So when you delete a property of your model it doesn't affect the SQL. Therefore, the required properties that are required from SQL you cannot change. You can use some typical characters to be filled in for a valid requirement from your SQL.

nhannt201
  • 31
  • 2
  • 5