Updated on Kisan Patel
This tutorial will show you how to inspecting individual validation errors in ModelState using Entity Framework.
Here are the Student
model with DataAnnotations attribute and StudentContext
class:
public class Student { public int Id { get; set; } [Required] public string Name { get; set; } [EmailAddress] public string Email { get; set; } } public class StudentContext : DbContext { public DbSet<Student> Students { get; set; } }
Now, here we have set the Student data with dummy value, but you can see the value of each property of Student model is wrong.
Student student = new Student(); student.Name = null; student.Email = "hsdfsdh";
So, how we know value of each property of Student model is wrong. By using GetValidationResult()
method you can read the errors as shown in below code:
using (StudentContext context = new StudentContext()) { var result = context.Entry(student).GetValidationResult(); foreach (DbValidationError error in result.ValidationErrors) { Console.WriteLine(error.ErrorMessage); } }
You can also validating individual properties on demand using GetValidationErrors() method as shown in below code:
var errors = context.Entry(student) .Property(t => t.Email) .GetValidationErrors(); Console.WriteLine(errors.SingleOrDefault().ErrorMessage);