Databases Reference
In-Depth Information
retrieve the error message using the ProductNameRequiredErrorMessage property of the
Resources class:
[Required(ErrorMessageResourceType = typeof( Resources ),
ErrorMessageResourceName = “ ProductNameRequiredErrorMessage ”)]
public object ProductName { get; set; }
Validation in Entity Framework
As of version 4, the Entity Framework offers only limited support for validation attributes
and requires additional work from developers. On one hand, the Entity Data Model
designer does not allow you to specify data annotations for entity classes and their proper-
ties, and on the other, the ObjectContext class does not validate entities before they are
saved.
NOTE
In version 4.1, the Entity Framework introduced support for validating entities when
they are saved. Unfortunately, it also introduced an entirely new API, which is not 100%
compatible with Dynamic Data at this time. The differences will not be fully reconciled
until the 4.5 release of the .NET Framework comes out. If you choose to use the
interim release, you need to make some of the same changes discussed in this
chapter.
Specifying Validation Attributes for Entity Classes
Because the Entity Data Model designer generates the entity classes in the . Designer.cs
file automatically, you cannot simply apply the validation attributes directly to the classes
and properties; they will get overwritten next time you update the entity model. Instead,
rely on the partial class syntax in C# and Visual Basic to extend the generated classes.
The code that follows shows an excerpt of the Product entity class as if it has been gener-
ated by the Entity Framework and therefore does not have the RequiredAttribute applied
to its ProductName property:
public partial class Product
{
public string ProductName { get; set; }
}
Notice that the class is declared as partial . This allows a separate file to extend the gener-
ated class and apply the MetadataTypeAttribute to specify an alternative type that will
supply validation attributes and other data annotations for the generated class:
using System.ComponentModel.DataAnnotations;
[MetadataType(typeof(Metadata))]
public partial class Product
{
 
Search WWH ::




Custom Search