ASP.Net MVC Entity Framework Entity Validation with DataAnnotation

entity framework data annotations database first entity framework validation database first add data annotations to a class generated by entity framework how to preserve data annotations when doing update from database entity framework validation before savechanges client side mvc metadata partial class entity framework metadata partial class entity framework example

Validation of Entity with Entity Framework is a tricky way, but it is really simple. In this article we will try to understand how easily we can add the validation with any entity created by Entity Framework with database first approach by using partial classes and pure DataAnnotation. We will not use any if.. else... or switch... case statement to validate different property. It will work with client side validation as well as server side vatlidation because we are going to use the dataannotation only.

Let's create a MVC application in Visual Studio (I am using 2015)

  • File - New - Project
  • Web - ASP.Net Web Application
  • Give any name say "CustomerPortal"
  • Click OK
  • Select "MVC" and click OK

It will create the project with a complete structure, it will take a litle bit time and let it complete.

Run the application, it should work with Home, About and Contact page.

Let's create the database for our application say "CustomerDB"

  • Right click on App_Data Folder, Add - New Item
  • Data - SQL Server Database
  • Name it "CustomerDB.mdf"
  • Click OK

Our database is created in our App_Data folder, double click on the database and add table

  • Right Click on Table - Add New Table

Add following script to create the table

CREATE TABLE [dbo].[Customer]
(
    [Id] INT NOT NULL PRIMARY KEY IDENTITY, 
    [FirstName] VARCHAR(20) NOT NULL, 
    [LastName] VARCHAR(20) NOT NULL, 
    [Address] VARCHAR(100) NOT NULL, 
    [Phone] VARCHAR(20) NOT NULL, 
    [Fax] VARCHAR(20) NULL, 
    [Email] VARCHAR(50) NULL, 
    [WebSite] VARCHAR(50) NULL
)

Click Update and then in opened model window click Update Database.

Now our database and table is ready to use, let's create the Endity Model in our Models folder:

  • Right click on Models Folder, Add - New Item
  • Data - ADO.Net Entity Data Model
  • Name it "CustomerModel"
  • Click Add
  • Select "EF Designer from database"
  • Click Next - Next
  • Select Table CheckBox and click Finish

Successfully we created our Entity Model, let's create a Customers controller in Controllers folder. Rebuild the application before creating the controller:

  • Choose "MVC 5 Controller with views, using Entity Frameworl"
  • Choose and enter value similar to the image
  • Click Add

Create Customer Controller

Run application and change Url to /customers. Complete feature Add, Edit, Detail and Delete all are working smoothly but not validating data.

Try to create a new customer and click create without providing any information, it will give error because validation is failed from database.

If we want, we can add the dataannotation code directly to the Customer entity and everything will work smooth. It is good until we change the database and update the Model from Database.

For permanent solution of above problem, we will create a new class inside the Models folder say "CustomerValidation.cs":

Mark this class as partial (it must be in the same namespace).

Copy all the properties from Customer.cs entity for which we want to add validation and paste them in our new class CustomerValidation and add dataannotation according to requirement.

After adding all the validation attributes, our CustomerValidation class will be:

public partial class CustomerValidation
{
    [Required]
    [Display(Name = "Firt Name")]
    [MaxLength(20, ErrorMessage = "Max 20 characters")]
    public string FirstName { get; set; }

    [Required]
    [Display(Name = "Last Name")]
    [MaxLength(20, ErrorMessage = "Max 20 characters")]
    public string LastName { get; set; }

    [Required]
    [Display(Name = "Customer Address")]
    [MaxLength(100, ErrorMessage = "Max 100 characters")]
    public string Address { get; set; }

    [Required]
    [Display(Name = "Customer Phone")]
    [MaxLength(12, ErrorMessage = "Max 12 characters")]
    public string Phone { get; set; }

    [MaxLength(12, ErrorMessage = "Max 12 characters")]
    public string Fax { get; set; }

    [MaxLength(50, ErrorMessage = "Max 50 characters")]
    public string Email { get; set; }

    [MaxLength(50, ErrorMessage = "Max 50 characters")]
    public string WebSite { get; set; }
}

Now we need to map this validation with our customer entity, for that add following lines after CustomerValidation class:

// Add this out of customerValidation class
[MetadataType(typeof(CustomerValidation))]
// Note the partial keyword
public partial class Customer { }

Final output with validation by adding metadata & validation

Note: after adding validation through metadata, we have not touched the controller or view because we don't need to change anything in controller or view. This also dictate the design pattern, business logic change should not need any change in user interface or controller (representation).

In this way we can add validation to any Entity and use the entity directly in view.

Ali Adravi Having 13+ years of experience in Microsoft Technologies (C#, ASP.Net, MVC and SQL Server). Worked with Metaoption LLC, for more than 9 years and still with the same company. Always ready to learn new technologies and tricks.
  • asp.net
  • mvc
  • validation
By Ali Adravi On 08 Jul, 18  Viewed: 2,756

Other blogs you may like

Readonly textbox postback issues and solutions

In many cases we need to use read only text box so user cannot edit the value but readonly textbox will lost its value after postback. Let’s say you have a read only text box to set date by using ajax calendar so after post back date will be lost, other case might be you are setting some value in... By Ali Adravi   On 24 Apr 2013  Viewed: 4,219

Call code behind method from JavaScript in asp.net

There are ways to call a web service method JavaScript, for more detail you can see [how to retrieve data from database using JavaScript in asp.net][1], but is there any way to call a normal method from JavaScript? And the answer is No; show how we can call a code behind method from JavaScript,... By Jonathan King   On 08 Apr 2013  Viewed: 12,445

Gridview paginated data with search and sort functionality in asp.net

Most of the times we need to use GridView control to show tabular data in our asp.net application. We simply write procedure to search the records and bind them with GridView and show 10 to 20 records per page. Have you ever thought that why you are fetching all the records and show only 10 to 20... By Ali Adravi   On 16 Feb 2013  Viewed: 8,387

ASP.Net 4.5 new feature Model Binding

A nice feature with ASP.Net is the model binding, it reduced our code and effort to bind our well know controls like GridView, DataList, Repeater etc. So let’s see how we can bind our old controls in new and easy way. Let’s see how we bind the our grid before 4.5 1. We write the code to get... By Mike .Net   On 17 Jan 2013  Viewed: 3,200

Upload multiple image in multiple size with progress bar in asp.net

In asp.net there is not control to select multiple files and upload them once with progress bar, so we will use a small third party DLL to achieve this functionality. We will use Flajaxian FileUploader, you can download it from [http://www.flajaxian.com][1] We will create three different images... By Hamden   On 12 Jul 2012  Viewed: 6,546