开发者

Can I add MVC 2 DataAnnotation attributes to existing properties?

开发者 https://www.devze.com 2022-12-13 14:22 出处:网络
I\'m using a generated class as a model, and I wish to add DataAnnotation attributes to some of its properties. As it\'s a generated code, I don\'t want to add the annotations directly. Is there anoth

I'm using a generated class as a model, and I wish to add DataAnnotation attributes to some of its properties. As it's a generated code, I don't want to add the annotations directly. Is there another way to attach them to a property?

I'd considered making the model an interface, and using a partial class to get the generated class to subscribe to it. Is there a开发者_JS百科 less elaborate solution, assuming that would even work?


Yes there is. You have to create metadata class that will have the same properties that your original model, and connect it to your model with MetadataType attribute:

[MetadataType(typeof(MyModelMetadata))]
public partial class OriginalMyModel
{
}

public class MyModelMetadata
{
    [Required]
    public string MyProperty;  

    // ...
}

In the example ebove OriginalModel is your proper model class, and MyModelMetadata is a class used only for annotating properties. MyModelMetadata should have the same properties that your model has.


You can use the MetadataType attribute on your class:

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.metadatatypeattribute.aspx

In practice, I've seen the metadata get out of sync with a generated model pretty frequently, though, which can lead to some headaches. You may want to look into an alternate validation mechanism instead of data annotations.

I've been using Fluent Validation, which is very easy to pick up and start using. There is even a Fluent Validation to xVal integration piece in Fluent Validation 2.0 (still in beta) that you can bring into your project for client-side validation.

Fluent Validation allows you to define your validation in a separate class. All you would need to do is add an attribute to your generated class telling it what validator to use, which could be accomplished through partial classes.

Alternatively, you could create view-specific models that are mapped to from your domain model that contain your data annotations. In that case, simplify the back-and-forth mapping using something like AutoMapper. Then, if your domain model changes, you get compile-time errors versus the metadata approach.

0

精彩评论

暂无评论...
验证码 换一张
取 消