Today, a colleague asked how to add a validation feature to the model when using the entity Framework's database frist or model first?
Because the model at this time is how the VS tool is generated, it is too realistic and unreasonable to directly add attribute to the Modle class. A more reasonable approach is to use the buddy class approach to achieve.
For example, there is a model class: Movie. Then we can add a local class file, the contents of the local class are as follows:
Using System.ComponentModel.DataAnnotations;
Namespace Movies.models
{
[Metadatatype (typeof (Moviemetadata))]
public partial class Movie
{
Class Moviemetadata
{
[Required (errormessage= "Titles are Required")]
public string Title {get; set;}
[Required (errormessage= "The Price is Required.")]
[Range (5,100,errormessage = "Movies cost between $ and $)]
Public decimal price {get; set;}
}
}
}
This is done by adding the required validation attributes to the local class file.
Reference:
Http://www.asp.net/mvc/tutorials/older-versions/getting-started-with-mvc/getting-started-with-mvc-part7
Http://weblogs. asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx
How to add validation attributes when ASP. NET MVC +. Nets EF Database First or model first