Why are buddy classes used for validation?

余生长醉 提交于 2019-11-28 08:38:48

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/5109785/why-are-buddy-classes-used-for-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!