Does it make sense to use MetadataType to enforce validations in case of Code First?

前端 未结 4 1610
情书的邮戳
情书的邮戳 2021-02-13 11:10

I seem to understand the reason behind taking help of MetadataTypeAttribute to Add Validation to the Model in case of Database First as we want to avoid the changes

4条回答
  •  攒了一身酷
    2021-02-13 11:35

    Does it make any sense to not apply these DataAnnotations on the actual Entity class directly and instead, separate these into partial class definitions and then link using MetadataType, even when using Code First approach to define Entity Model?

    In most of the cases it doesn't make sense because it involves unnecessary and redundant code duplication just to associate some attributes with the properties.

    It doesn't make sense if the entity class model is created by you with code.

    It also doesn't make sense if it's created with some custom code generation you have control over (like T4 template) because you can customize the generation itself.

    The only case when it makes sense is when you have no control over the entity class code (for instance, the class coming from 3rd party library). In such case, you can use AssociatedMetadataTypeTypeDescriptionProvider class to associate metadata with the 3rd party class.

    For instance, let say the following class is coming from another library with no source code:

    public sealed class ExternalEntity
    {
        public string Name { get; set;}
    }
    

    Then you can define the metadata class:

    public class ExternalEntityMetadata
    {
        [Required]
        public string Name { get; set;}
    }
    

    and associate it with the ExternalEntity using TypeDescriptor.AddProvider method once (during the application startup or something):

    TypeDescriptor.AddProvider(new AssociatedMetadataTypeTypeDescriptionProvider(
        typeof(ExternalEntity), typeof(ExternalEntityMetadata),
        typeof(ExternalEntity));
    

提交回复
热议问题