Can I add MVC 2 DataAnnotation attributes to existing properties?

时光总嘲笑我的痴心妄想 提交于 2019-12-10 10:26:39

问题


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 less elaborate solution, assuming that would even work?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/1882338/can-i-add-mvc-2-dataannotation-attributes-to-existing-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!