为什么用于验证哥们班? [英] Why are buddy classes used for validation?
问题描述
我很好奇,为什么数据验证使用好友类完成的。考虑下面的例子,其中 myEntity所
是一个LINQ到SQL或LINQ到实体的实体,和下面的类是局部类增强实体。
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; }
}
}
为什么设计这样的吗?当他们设计的DataAnnotations,为什么这个哥们模式选择?为什么不直接将属性的实体?
Why is the design so? When they designed DataAnnotations, why was this "buddy pattern" selected? Why not place the attributes directly in the entity?
推荐答案
原因很现实 - 在LINQ到SQL和LINQ到实体时,code再presenting类再生每次对象模型被更新。为了使发生这种情况时不被覆盖的注释,他们需要在一个单独的伙伴类。
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.
这篇关于为什么用于验证哥们班?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!