In order to experience the new features of Entity Framework I created a new MVC 4 internet application.
I connected it to an existing database and generated the Model classes with the dbContext generator.
By running the application I got some validation errors while editing a form. As example for a DateTime field the system was complaining if the date was inserted as “12/10/2012” instead of 2012-10-12 (as in the SQ Server notation).
I tried to find the validation code in the project, but I could not find it anywhere in the generated code.
One of my model classes is the following:
public partial class Artist
{
public Artist()
{
}
public int Id { get; set; }
public string Name { get; set; }
public Nullable<System.DateTime> DateOfBirth { get; set; }
public virtual Countries Countries { get; set; }
}
How can I customize the validation errors if using the Database first approach?
If I decor the models with my validation attributes, then they would be erased once the model classes are generated again.
Moreover in a “real world” project where the use of an existing database is mandatory, what would be the best approach with the development of the model classes?
Extending the classes automatically generated by adding partial classes with the same name?
EDIT (Introduced part of the View):
@using (Html.BeginForm()) {
@Html.ValidationSummary(false)
<fieldset>
<legend>Movie</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.DateOfBirth)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.DateOfBirth)
@Html.ValidationMessageFor(model => model.DateOfBirth)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
Well, you can always use a metadata class
and a partial class
Or (my preferred solution) you can use an external Validation library, like the excellent FluentValidation
You have a “basic” validation by default (which can be removed in the global.asax), checking : that the non nullables values… are not null (like a default Required attribute), and that values are of the right type.