//
you're reading...
asp.net mvc, Entity Framework

Validation Metadata and Entity Framework

When using the Entity Framework it is challenging to associate attributes with the database properties defined in the context. The .Net Framework provides a solution to this problem with its MetadataType attribute. The steps to implementing this functionality is:

    • Create your Entity Framework model. (In this particular example I’m working with a JobScheduler database that manages computer programs to be run on a particular schedule. Not really important for this post but it does provide a context.)
    • I’m going to add validation to the “Title” property of the “Job” class. In theory we would want to add the following code:

<br />
Imports System.ComponentModel.DataAnnotations</p>
<p>Partial Public Class Job</p>
<p><Required(ErrorMessage:="Title is required")> _<br />
Public Property Title As String</p>
<p>End Class<br />

    • Unfortunately the above approach generates errors no matter what you try to do. (Really!)
    • Instead, what we are going to do is the following:

<br />
Imports System.ComponentModel.DataAnnotations</p>
<p><MetadataType(GetType(Job_Extensions))> _<br />
Partial Public Class Job</p>
<p>End Class<br />

    • Referencing the “Job_Extensions” type will generate a “Type not found” error. So, let’s create it.
    • Add the following class definition to your project:

<br />
Imports System.ComponentModel.DataAnnotations</p>
<p>Public Class Job_Extensions</p>
<p>    <Required(ErrorMessage:="Title is required")><br />
    Public Title As Object</p>
<p>End Class<br />

  • Note that “Title” does not need to be defined as a property nor does its type need to match the database definition.
  • In this manner metadata is added to Entity Framework controlled properties.
Advertisement

About art colman

XML tools and consulting for standards development.

Discussion

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.