Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are buddy classes used for validation?

I am curious as to why data validation is done using buddy classes. Consider the following example, where MyEntity is a Linq-to-SQL or Linq-to-Entities entity, and the class below is a partial class enhancing the entity.

[MetadataType(typeof(MyEntity.MyEntityMetadata))]
public partial class MyEntity
{
    private class MyEntityMetadata
    {
        [Required(ErrorMessage = "The title is required.")]
        public string Title { get; set; }
    }
}

Why is the design so? When they designed DataAnnotations, why was this "buddy pattern" selected? Why not place the attributes directly in the entity?

like image 631
kbrimington Avatar asked Feb 24 '11 20:02

kbrimington


2 Answers

I assume this prevents generated entities from overwriting custom Meta Data information.

like image 70
Michael Merrell Avatar answered Oct 03 '22 16:10

Michael Merrell


The reason is practical - in linq-to-sql and linq-to-entities, the code representing the classes regenerated every time the object model is updated. In order for the annotations not to be overwritten when this happens, they need to be in a separate "buddy" class.

If you're using Data Annotations in a different context - say for a view model - then they can go on the original class itself.

like image 23
James Sulak Avatar answered Oct 03 '22 15:10

James Sulak