Over a million developers have joined DZone.

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

Build APIs from SQL and NoSQL or Salesforce data sources in seconds. Read the Creating REST APIs white paper, brought to you in partnership with CA Technologies.

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()
        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.

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

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();
        public ActionResult Create([Bind(Include = "ID,FirstName,LastName,Phone,Email")] Student student)
            StudentValidation val = new StudentValidation();
            ValidationResult model = val.Validate(student);
            if (model.IsValid)
                return RedirectToAction("Index");
                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.

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.

The Integration Zone is brought to you in partnership with CA Technologies.  Use CA Live API Creator to quickly create complete application backends, with secure APIs and robust application logic, in an easy to use interface.

asp.net,entity framework code first,fluent api

Published at DZone with permission of Ahmed Abdi. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}