Does it make sense to use these DataAnnotations directly in the actual Entity class and instead separate them into partial class definitions and then reference MetadataType even if you use the Code First approach to define the Entity Model?
In most cases, this does not make sense, because it involves unnecessary code duplication in order to associate some attributes with properties.
It makes no sense if you create an entity class model with code.
It also makes no sense if it is created using a specific user code that you control (for example, the T4 template), because you can customize your own generation.
The only case where this makes sense is when you do not have control over the code of an entity class (for example, a class coming from a third-party library). In this case, you can use the AssociatedMetadataTypeTypeDescriptionProvider class to map metadata to a third-party class.
For example, let's say the following class comes from another library without source code:
public sealed class ExternalEntity { public string Name { get; set;} }
Then you can define a metadata class:
public class ExternalEntityMetadata { [Required] public string Name { get; set;} }
and associate it with ExternalEntity using the TypeDescriptor.AddProvider once (at application startup time or something else):
TypeDescriptor.AddProvider(new AssociatedMetadataTypeTypeDescriptionProvider( typeof(ExternalEntity), typeof(ExternalEntityMetadata), typeof(ExternalEntity));
Ivan Stoev
source share