文章目錄
- Adding Validation to the Model
Adding Validation to the Model
In this section we'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 to the Movie
class.
Open the Movie
class file. We'll add attributes from the System.ComponentModel.DataAnnotations namespace, so you need to add a using
statement for System.ComponentModel.DataAnnotations
. We'll apply the Required attribute and the Range attribute. The Required
attribute makes a field required; in the sample, the user will have to enter a title. The Range
attribute constrains the field within the specified range.
The following code shows the Movie
class 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 includes 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.
The Connect to Server dialog box is displayed.
In the Server name box, enter the following name:
./SQLEXPRESS
Click Connect. The Movies database is displayed in the Object Explorer pane on the left.
Right-click the Movies database and select Delete.
(If you've got data that you want to save, you can export it from the Movies database using SQL Management Studio before you delete the database.)
In the Delete dialog box, make sure the Close existing connections check box is selected, then click OK. The Movies database is now deleted.
Run the application. A new database is created that includes the recent changes to the Movie
class. In the browser, navigate to /Movies/Create and 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 mechanism that created the view. Open the Movies/Create.cshtml file. 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 notify users if the data they entered is not valid. Next, let's add a new column to the database.