Document directory
- Adding validation to the model
Adding validation to the model
In this section we're re going to implement the support necessary to enable input validation in the application. we'll ensure that database content is correct and provide helpful error messages to end users when they try to enter movie data that isn' t valid. we'll begin by adding a little validation logic toMovieClass.
OpenMovieClass file. We'll add attributes from the system. componentmodel. dataannotations namespace, so you need to addusingStatementSystem.ComponentModel.DataAnnotations. We'll apply the required attribute and the range attribute.RequiredAttribute makes a field required; in the sample, the user will have to enter a title.RangeAttribute constrains the field within the specified range.
The following code showsMovieClass with these two attributes applied.
public class Movie { public int ID { get; set; } [Required] public string Title { get; set; } public DateTime ReleaseDate { get; set; } public string Genre { get; set; } [Required] [Range(5, 100, ErrorMessage = "The price must be between $5 and $100")] public decimal Price { get; set; } }
The attributes are applied not only to the model; when you use the code-first approach, Entity Framework applies them to the database. Run the application and you see the following error:
The model backing the 'MovieDBContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance
You're seeing this error because in the code-first approach, Entity Framework automatically created the database, and by default when it creates a database, it adds a table that helps tracks whether the schema of the database is in sync with the model classes. entity Framework throws an error if they become out of sync, which makes it easier to track down issues sat development time That you might otherwise find (by obscure errors) only at run time.
There are two basic approaches to solving this problem:
- Have Entity Framework automatically re-create the database based on the new model class schema. The downside of this approach is that you lose all existing data.
- Modify the schema of the existing database to sync it with the model classes. the advantage of this approach is that you keep your data. the disadvantage is that you have to make the same change in two places (in your model and in the database schema ).
For this tutorial, We'll delete the database. A new one that has des our changes will be automatically created the next time we run the application. to delete the movies database, we'll use SQL management studio express 2008. if you don't already have this free database utility, you can use the Web Platform installer to download and install it.
Start SQL Server Management studio.
TheConnect to serverDialog box is displayed.
InServer NameBox, enter the following name:
./Sqlexpress
ClickConnect. The movies database is displayed inObject ExplorerPane on the left.
Right-clickMoviesDatabase and selectDelete.
(If you 've got data that you want to save, you can export it fromMoviesDatabase Using SQL management studio before you delete the database .)
InDeleteDialog box, make sureClose existing connectionsCheck box is selected, then clickOK.MoviesDatabase is now deleted.
Run the application. A new database is created that includes des the recent changes toMovieClass. In the browser, navigate/Movies/createAnd try to create a new movie with a price outside the specified range.
The price range error is displayed as soon as you tab out of the price field, before you submit the form. the client-side validation was enabled by the scaffolding mechanic that created the view. openMovies/create. cshtmlFile. The following two lines enable client-side jquery validation.
<script src="@Url.Content("/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
This is looking good! We 've got client validation to immediately specified y users if the data they entered is not valid. Next, let's add a new column to the database.