model-view-controllervalidationinterfacedata-annotationsmetadatatype

When using Data Annotations with MVC, Pro and Cons of using an interface vs. a MetadataType


If you read this article on Validation with the Data Annotation Validators, it shows that you can use the MetadataType attribute to add validation attributes to properties on partial classes. You use this when working with ORMs like LINQ to SQL, Entity Framework, or Subsonic. Then you can use the "automagic" client and server side validation. It plays very nicely with MVC.

However, a colleague of mine used an interface to accomplish exactly the same result. it looks almost exactly the same, and functionally accomplishes the same thing. So instead of doing this:

[MetadataType(typeof(MovieMetaData))]
public partial class Movie
{
}

public class MovieMetaData
{
    [Required]
    public object Title { get; set; }

    [Required]
    [StringLength(5)]
    public object Director { get; set; }


    [DisplayName("Date Released")]
    [Required]
    public object DateReleased { get; set; }
}

He did this:

public partial class Movie :IMovie
{
}

public interface IMovie
{
    [Required]
    object Title { get; set; }

    [Required]
    [StringLength(5)]
    object Director { get; set; }


    [DisplayName("Date Released")]
    [Required]
    object DateReleased { get; set; }
}

So my question is, when does this difference actually matter?

My thoughts are that interfaces tend to be more "reusable", and that making one for just a single class doesn't make that much sense. You could also argue that you could design your classes and interfaces in a way that allows you to use interfaces on multiple objects, but I feel like that is trying to fit your models into something else, when they should really stand on their own. What do you think?


Solution

  • I like your interface approach as it allows you to define a contract for your model which you can use to adapt your ORM generated classes to. That would allow you to decouple your app from the ORM framework and get more use out of the MetadataType interface as it serves as data validation metadata as well as a contract for your model. You could also decorate your interface with serialization attributes for use in WCF gaining more use out of the interface. I followed a few early blogs that recommended creating a metadata class but again I think the interface solution is a nice idea.