Databases Reference
In-Depth Information
LISTING 1.9
Extending Product Metadata Using Data Annotations
using System;
using System.ComponentModel.DataAnnotations;
namespace DataModel
{
[MetadataType(typeof(Product.Metadata))]
partial class Product
{
public abstract class Metadata
{
[Display(Name = “Units in Stock”)]
public object UnitsInStock { get; set; }
}
}
}
Notice that the Product class is declared with the
partial
keyword. This effectively
extends the definition of the Product entity class generated by the Entity Framework
designer, making everything in this code snippet a part of the generated Product class.
This is necessary because you cannot place the
DisplayAttribute
directly on the gener-
ated UnitsInStock property. Any changes made in the generated code by hand will be lost
the next time the code is regenerated. Instead, you define a separate class (called
Metadata
in this example) and use the
MetadataTypeAttribute
to associate it with the entity class,
Product. Any data annotation attributes placed on the properties of the Metadata class will
have the same effect as if they were placed on the actual properties of the Product class,
such as the UnitsInStock in this example. After making these changes, the error message
displayed by the
Integer_Edit
field template when the user enters alphabetic symbols in
the UnitsInStock field will include the human-readable display name.
Metadata used by Dynamic Data includes not only information about individual columns,
but also the information about entire tables. If you need to build a data entry page that
includes all fields of the Products table, you can replace all individual
DynamicControl
instances with a single
DynamicEntity
control.
LISTING 1.10
DynamicEntity and Entity Template Sample (Markup)
<%@ Page Language=”C#”
MasterPageFile=”~/Site.master” CodeBehind=”SamplePage.aspx.cs”
Inherits=”WebApplication.Samples.Ch01.EntityTemplate.SamplePage” %>
<asp:Content runat=”server” ContentPlaceHolderID=”main”>