Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Code First Model Validation With a Fluent API

DZone's Guide to

Code First Model Validation With a Fluent API

See how you can validate your data using a fluent API. Learn step by step how to set up your database and check your inputs against the correct information.

· Integration Zone ·
Free Resource

Learn more about how to Prevent Slow or Broken APIs From Affecting Your Bottom Line.

In this article, we are going to learn how to validate types by using fluent validation. We can either do with Data annotation or a fluent API. The simplest way for model validating is by just using data annotation, but if  you want your domains to be clean, then the fluent validation is the preference.

Let's Begin

Step1: Create a new web application and select MVC template, and then Install the entity framework and fluent validation  from nuggets.

Step 2: Next in the model folder, add a Student class

public class Student {
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Phone { get; set; }
    public string Email { get; set; }
}


Step 3: Next, we are to going to create context class. Add a new class, Studentcontext, inside the DAL folder.

namespace MvcModelValidation.DAL
{
    public class StudentContext : DbContext
    { 
        public StudentContext()
        :base("stddb")
        {
            Database.SetInitializer<StudentContext>(null);
        }
        public DbSet<Student> Students { get; set; }
    }
}


Step 4: Now create a folder in the root of the project and add the studentvalidation class. As we can see, our Student validation class inherits AbstractValidator, and this class allows us to define a set of validation  rules.

namespace MvcModelValidation.Validations
{
    public class StudentValidation : AbstractValidator<Student>
    {
        public StudentValidation()
        {
           RuleFor(c => c.FirstName).NotEmpty().Length(0,10);

            RuleFor(c => c.LastName).NotEmpty().Length(0,10);

            RuleFor(c => c.Phone).Length(10).WithMessage("Enter valid number");

            RuleFor(c => c.Email).EmailAddress();
        }
    }
}


Step 5: Add a connection string in the Web Config file located in the root.

<connectionStrings>
 <add name="stdb" providerName="System.Data.SqlClient" connectionString="Data Source= MMC-PC\SQLEXPRESS;Initial ;Integrated ;" />
 </connectionStrings>


Step 6: Next, add a new controller. In our controller, we are only working with two actions — one for using as input and other for displaying data passed with no validation errors.

namespace MvcModelValidation.Controllers
{
    public class StudentsController : Controller
    {
        private StudentContext db = new StudentContext();
        //Get Students
        public ActionResult Index()
        {
            return View(db.Students.ToList());
        }
        // GET: Students/Create
        public ActionResult Create()
        {
           return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "ID,FirstName,LastName,Phone,Email")] Student student)
        {
            StudentValidation val = new StudentValidation();
            ValidationResult model = val.Validate(student);
            if (model.IsValid)
            {
                db.Students.Add(student);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            else
            {
                foreach (ValidationFailure _error in model.Errors)
                {
                    ModelState.AddModelError(_error.PropertyName, _error.ErrorMessage);
                }
            }
            return View(student);
        }
    }
}


Step 7: Now we need to enable migrations to prepare the database. Run the following commands in the package manager console, but before that, build the project to check it’s running without errors.

enable-migrations      
add-migration "initial-migration"
update-database -verbose


Step 8: Now we are done, and database is created. Let's fire our application and insert some invalid data.

Image title

Now insert some  valid data

Image title


And there you have it. All done.

Learn about the Five Steps to API Monitoring Success with Runscope

Topics:
asp.net ,entity framework code first ,fluent api

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}