boutique replica bags up ideas

the best replique rolex and prices here.

julia highlight 99j hair color 10a quality straight human hair lace front wigs 8 - 24 inches pre plucked hairline 13x4 inches lace front brazilian wig onlinefor sale

Get individual Validation Errors in ModelState using Entity Framework

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);
     }
}

DbValidationError-demo

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);

Download Complete Source Code


Entity Framework

Leave a Reply