Skip navigation

More Fun with Dynamic Data in Visual Studio 2010

Further insights into validation with Dynamic Data

Downloads
Bruney DCM094 DDExample1.zip

Click here to download the code for this article.


In my article, "Using Dynamic Data in Visual Studio 2010," I discussed Dynamic Data in some detail and showed a quick example of its power. In this article, I want to focus a bit more on the specifics of validation. I'll also provide some guidance on using Dynamic Data. As I pointed out in the previous article, validation is provided automatically; the entity model has intimate knowledge of the underlying data store, so that it can perform validation by comparing the entity properties against the data store schema. Allow me to demonstrate this.

Open the DDExample1 project (click the Download link at the top of this article to download a .zip file containing DDExample1) and Select Server Explorer from the View menu. Add a new column to the KingOfPop table by right-clicking on the table and choosing Open Table Definition, as Figure 1 shows. Recall from the last article, the KingOfPop database is a test database with sample data.

Enter Count as the name of the column and set its type to Int (integer). Make sure to check the Allow Null field; the ALTER TABLE command that Visual Studio uses to create the new column requires that the data type column allow null data. Double-click the DDModel.edmx file in Solution Explorer to launch the Entity Designer, as in Figure 2.

Right-click the entity widget in the designer and choose Update Model from Database…. Run the application by pressing Ctrl+F5. The shortcut key action bypasses the debugger, allowing the validation mechanism to handler the error. Figure 3 shows that I tried to insert a string in the Count field. The entity model determines that the type is incorrect and fires the validation exception circuitry.

There are two things to note here. First, you can't even think of pulling off this stunt on home-grown code! If you change the schema, the code will either fall over dead or the new column will not propagate to the front end. Period! Second, notice the effort involved.

Now, consider that you want to provide validation based on business rules, the kind that can't be easily defined and validated by relying on the compiler. For instance, consider that the count field must only contain numerical values between 1 and 10. I'll first need to create a partial class with a name that exactly matches the entity model. The partial keyword will extend the class to include the custom code that I will write. The runtime will use the code inside this class to apply validation to the model automatically. The following listing shows the complete code.

using System;
using System.ComponentModel.DataAnnotations;
namespace DDExample1
\\{
    \\[MetadataType(typeof(KingOfPopMetadata))\\]
    public partial class KingOfPop
    \\{
        partial void OnCountChanging(int? value)
        \\{
            if (value < 1 || value > 10)
            \\{
                throw new ValidationException("Enter a valid count between 1 and 10.");
            \\}
        \\}
    \\}
    public class KingOfPopMetadata
    \\{
        \\[ScaffoldColumnAttribute(false)\\]
        public object ID \\{ get; set; \\}
        \\[ScaffoldColumnAttribute(true)\\]
        \\[Required(ErrorMessage = "Title is required.")\\]
        public object Author \\{ get; set; \\}
    \\}
\\}

There are two classes in the DDExample1 namespace. The namespace is required when extending the model using partial classes. Otherwise, the class will compile cleanly but the types will be ignored at run-time. The first class implements the run-time validation code. The second class provides metadata to the run-time. The metadata will help annotate the model. The two classes are tied together using the special metadatatype attribute. Inside the OnCountChanging method, I implement the business rules. The exception thrown in my business rule is handled entirely by the validation circuitry, as Figure 4 shows.

Notice that the declared parameter in the OnCountChanging method is a nullable type to match the underlying data store null attribute. Recall that the column field was set to allow nulls. OnCountChanging is provided by the entity model automatically and is defined in the DDModel.Designer.cs file.

Just for grins, I annotated the KingOfPopMetadata class to provide more custom functionality. For instance, the ScaffoldColumnAttrubute, set to false, informs the runtime that the ID field should not be displayed to the user. Strictly speaking, this is redundant; the model already infers that from the primary key associated with the column so it is hidden by default.

By the same token, I make the Author field visible by setting the corresponding attribute to true. I've also taken the liberty to add more custom validation to the Author field using the RequiredAttribute attribute with a custom message. You can inject functionality by using predefined attributes such as the RangeAttribute or DataTypeAttribute attribute as well. The former validates against numerical ranges, the latter formats data types in date format.

In the code download for this article, I've gone a step further by implementing validation using custom attributes. That way, I simply annotate the model with a custom attribute called CustomAttribute. The attribute is applied to the Title field and causes validation to kick-in automatically when the length of the Title field is less than three characters long. Powerful stuff!

Guidance

  • Consider using Dynamic Data if you want to take advantage of the Entity Framework and its data modeling infrastructure.
  • If you put a premium on time-to-market for line-of-business data-driven applications, Dynamic Data should rank at the top of your list.
  • Finally, consider Dynamic Data if you would like to build software that is less brittle; that is, the application can tolerate data store schema changes.
  • Avoid Dynamic Data if you need rich functionality from a wide range of server controls. You can find more information on Dynamic Data at this link: http://msdn.microsoft.com/en-us/library/cc488545.aspx.

Alvin Bruney is a longtime Microsoft MVP and author. His new book, ASP.NET 4 by Example, is available on www.lulu.com/owc.

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish