Splitting DataAnnotations into Another File Using MetaDataType

Some developers prefer the model classes as clean as possible, therefore preferring not to add DataAnnotations to them. This is achieved by using a MetaDataType class as follows.

Add a new class to the Models folder called ProductMetaData.cs and update the contents of the file to
the following code:

using System.ComponentModel.DataAnnotations;

namespace BabyStore.Models
{
    [MetadataType(typeof(ProductMetaData))]
    public partial class Product { }
    public class ProductMetaData
    {
        [Display(Name = "Product Name")]
        public string Name;
    }
}

This declares the Product class as now being a partial class, meaning it is split across multiple files. The
DataAnnotation [MetadataType(typeof(ProductMetaData))] is used to tell .NET to apply metadata to the
Product class from the ProductMetaData class.

namespace BabyStore.Models
{
    public partial class Product
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public decimal Price { get; set; }
        public int? CategoryID { get; set; }
        public virtual Category Category { get; set; }
    }
}

Source: ASP.NET MVC with Entity Framework and CSS, Naylor L., pp. 38

MVC

MVC stands for Model-View-Controller and is a recognized design patterns for developing software applications. ASP.NET MVC based applications are made up of:

  • Models – These are classes that model the data of the application.
  • Views – These are templated files that generate HTML to be sent to the web browser. A view typically deals with displaying data from a model.
  • Controllers – These are classes that process incoming requests, obtain data model, and typically return this data to a view for displaying as HTML. Controllers may contain logic for filtering data based on information sent by the request.

Source: ASP.NET MVC with Entity Framework and CSS, Naylor L., pp. 1