Introduction
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:
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 works 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 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. Let's look at an example of how to use the MetadataType
attribute:
public class CRMTypeMetadata
{
[ScaffoldColumn(false)]
public int TypeID { get; set; }
[StringLength(100)]
public string Url { get; set; }
}
[MetadataType(typeof(CRMTypeMetadata))]
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 holds 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.
Summary
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.