Over a million developers have joined DZone.

Adding Metadata to Entities in The Data Model

DZone's Guide to

Adding Metadata to Entities in The Data Model

· ·
Free Resource

Sometimes I’m being asked how to add metadata to a generated entity in Entity Framework. This metadata can be data annotation or other attributes which can help the developer during runtime. One answer that I give is to edit the T4 template in order to add the attributes. This solution can be combined with the building of an extension to Entity Framework designer which can add more details to the EDM. But it can take some time to develop. Another solution is to create a MetadataType for the entity and use the entity’s partial class behavior to add this type. This post will show you the second solution.

Adding Metadata to a Generated Entity

In the example I’m going to use the following simple entity:
Entity Designer Diagram

This type is part of a Dynamic Data site and the requirements for it are not to show the TypeID and that the Url needs to be up to 100 characters. Since Dynamic Data work with Data Annotations I want to add this metadata to the entity. But the problem is that the entity is generated by Entity Framework code generation. So how can I add the annotations? using the MetadataType attribute. The MetadataType is an attribute that is part of the System.ComponentModel.DataAnnotations assembly. It indicates that the a data model class has an associated metadata class. The MetadataType attribute gets a type parameter to specify which type is holding the metadata for the class. We can use the fact that the entity is generated as partial class and add the MetadataType attribute to it. Lets look at an example of how to use the MetadataType attribute: 

public class CRMTypeMetadata
public int TypeID { get; set; }

public string Url { get; set; }

public partial class CRMType

The first thing to notice in the example is that I’ve created a public class by the name CRMTypeMetadata which hold the properties annotated with the relevant attributes. The Metadata postfix in the class name is a convention that I encourage you to use. After I create the metadata class all I need to do is to create a partial class for the generated entity and annotate it with the MetadataType attribute. The MetadataType attribute will get as a parameter the type of the metadata type which is CRMTypeMetadata in the example. That is all.
Now the expected behavior was achieved.


One of the solutions to add metadata to entities in the Entity Data Model is by using the MetadataType attribute. It is very simple to use and can help you in frameworks like ASP.NET MVC, Dynamic Data, WCF Ria Services and more.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}