为什么用于验证哥们班?哥们

由网友(迟暮残存余温)分享简介:我很好奇,为什么数据验证使用好友类完成的。考虑下面的例子,其中 myEntity所是一个LINQ到SQL或LINQ到实体的实体,和下面的类是局部类增强实体。I am curious as to why data validation is done using buddy classes. Consider the...

我很好奇,为什么数据验证使用好友类完成的。考虑下面的例子,其中 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.

阅读全文

相关推荐

最新文章