Sunday, March 4, 2012

Using MetaData Classes in MVC

A meta data class is a class that defines something that could not be done in the class in the higher level. One of the key reasons that you would need meta classes is when you are using the Entity Framework. It is useless that you modify the validation controls in the Entity Model as it will be rebuilt when you build or debug the application. So the code that you added later to validate will not be there for any more.

In such cases, Meta classes will be useful. It’s just a matter of creating a new class and adding a sort of a reference to it in the entity class generated by the Entity Framework. This is quite simple.
For example, I am going to use a sample class named Customer in order to validate it from outside.
1
2
3
4
5
6
public class CustomerMeta
{
    [Required()]
    public string Name;
    //More code goes here
}
Now add the MetadataType attribute to the class located in Entity Framework. This will not be removed per each rebuild of the application.
1
2
3
4
5
6
[MetadataType(typeof (CustomerMetaData))]
public partial class Customer
{
    public string Name;
   //Variable and method declarations
}
At last, you will have to gets two using statements for both the classes. I will let you know what they are.

No comments:

Post a Comment