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)
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"
Our database is created in our App_Data folder, double click on the database and add 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:
Successfully we created our Entity Model, let's create a Customers controller in Controllers folder. Rebuild the application before creating the 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 { }
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.
![]() |
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.
|
By Ali Adravi On 08 Jul, 18 Viewed: 2,754 |
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,217
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
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,383
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
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