Use EF code first and ASP. NET mvc3 for class-level model verification

Source: Internet
Author: User

You can apply the verification attribute) -- such. net 4 built-in [required], [range] -- [regularexpression] To your model class, so as to ensure that the validity of the model attribute is verified before it is stored in the database. You can also generate your own custom verification attributes like this cool [creditcard] validator) and automatically enforce them through EF code first. This is a simple way to verify the attribute value in your model. I have shown some examples of this operation in my previous blog.Code.

Use ivalidatableobject to implement class-level model verification

Data annotation properties provide a simple method to verify a single attribute value in your model class.

Some people asked: Does EF code first also support Class-level verification methods on Model objects, simply verifying rules without involving many attribute values? The answer is yes-you have a very simple method to implement: implement the ivalidatableobject interface in your model class.

Ivalidatableobject. Validate () method

The following is an example of using the ivalidatableobject interface (included in the. net4 system. componentmodel. dataannotaions namespace) in the product model class to implement two custom verification rules. These two rules guarantee:

· If the product is out of stock, the new unit cannot be ordered.

· If the inventory exceeds 100 units, new items (units) cannot be ordered

We will enforce these business rules by implementing the ivalidatableobject interface in our product class and its validate () method, like this:

The ivalidatableobject. Validate () method can apply verification rules involving multiple attributes and return multiple verification errors. Each returned verification result provides an error message and a list of candidate attribute names that cause verification conflicts (this is useful for displaying error messages in the UI ).

Force Automatic Verification

When the model object implementing the ivalidatableobject interface is saved, EF code first (since ctp5) will now automatically call the validate () method. You don't need to write any code to implement it-this is now supported by default.

This new support means that the code that violates the preceding commercial rule will be called in the northwind. when dbcontext's "savechanges ()" method is used, an exception is automatically thrown (and the transaction is aborted ).

In addition to handling verification exceptions, EF code first also allows you to actively check for verification errors. Starting from ctp5, you can call the getvalidationerrors () method of the dbcontext base class to return a validation error in a column of Model objects to be processed. Getvalidationerrors () returns all verification errors-whether they are generated using the data annotation attribute or ivalidatableobjectvalidate.

The following example shows how to use

Example of an error actively checking the getvalidationerrors () method:

ASP. NET mvc3 and ivalidatableobject

For Model Objects used together with the model binding structure of ASP. net mvc, ASP. NET MVC2 supports automatic forcible implementation of its data annotation attributes. ASP. NET mvc3 goes further, and it also supports the ivalidatableobject interface. When a verification error occurs, this comprehensive support for model verification simplifies the error information in the display window.

To demonstrate this operation, let's look at a simple create window that allows users to generate new products:

We can use a productcontroller class containing the following two methods to implement the above two create functions:

The first create () method implements a/product/create URL to process HTTP-GET requests and display HTML forms for filling. The second create () method implements another/product/create URL to process the http-POST request-It retrieves the submitted form data to ensure its validity, if it is valid, save it in the database. If there is a problem with the verification, it will re-display the form and the value it submitted.

The razor view template of our "CREATE" View (which describes the form) is similar to the following:

One of the highlights of the implementation in the Controller view above is that we did not write any verification logic in it. Verify that the logic and business rules are fully implemented at our model layer, the productscontroller simply checks whether it is valid and calls the modelstateisvalid helper method to decide whether to save the changes or re-display the form with errors. Our view calls

The HTML. validationmessagefor () helper method only displays the error messages returned by the Data annotation and ivalidatableobject. Validate () Methods of our product template.

We can input illegal data in the form and try to submit and reproduce the above scenario.

Note how we get an error message when we click "CREATE. This is because we have selected the "discontinued" check box and entered a unitsonorder value (which violates one of our business rules ).

You may ask: how does ASP. net mvc know to highlight the error message next to the unitsonorder text box? This is because ASP. net mvc 3 supports the ivalidatableobject interface when implementing model binding. It returns an error message indicating that the verification fails.

The business rules in our product model class specify that when our business rules are violated, the "unitsonorder" attribute must be highlighted.

Because of the property name prompt above, our HTML. validationmessagefor () helper method knows to display the business rule error message next to the unitsonorder edit box:

Keep the code "dry" (dry: Don't repeat yourself)

ASP. net mvc and EF code first allow you to place verification and business rules in the same place (in your model layer) to prevent them from slipping into your controller and view.

Placing verification logic at the model layer can help prevent you from accessing the application.ProgramWhen adding more controllers and views, repeat the verification/business logic. It allows you to quickly change your business rules/verification logic in one place (in your model layer) and immediately reflect it in all controllers/views in your application. This makes your program code clean, easy to maintain, and easy to evolve and upgrade in the future.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.