Over a million developers have joined DZone.

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

Discover how developers can easily discover existing APIs and back-end data sources and create new APIs and microservices based on the popular open-source Node.js Express and LoopBack® frameworks.  Brought to you in partnership with IBM.

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.

Learn about the comprehensive capabilities to create, run, manage, secure and monetize APIs and microservices with API Connect.  Brought to you in partnership with IBM.

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