Where to put data annotations tags?

2019-07-18 15:42发布

问题:

I am going through pro asp.net mvc 2.0 framework and it seems that he puts his data annotation tags on classes that also generate the linq to sql.

  [Table(Name = "Products")]
    public class Product
    {
        [HiddenInput(DisplayValue = false)]
        [Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
        public int ProductID { get; set; }

        [Required(ErrorMessage = "Please enter a product name")]
        [Column] public string Name { get; set; }

        [Required(ErrorMessage = "Please enter a description")]
        [DataType(DataType.MultilineText)]
        [Column] public string Description { get; set; }

        [Required]
        [Range(0.01, double.MaxValue, ErrorMessage = "Please enter a positive price")]
        [Column] public decimal Price { get; set; }

        [Required(ErrorMessage = "Please specify a category")]
        [Column] public string Category { get; set; }

        [Column]
        public byte[] ImageData { get; set; }

        [ScaffoldColumn(false)] [Column]
        public string ImageMimeType { get; set; }

However I am wondering what happens if I don't develop my database this way. What happens if I just add to my solution a linqtosql.dbml ( linq to sql class) file where I get that nice designer.

Where would I put all these data annotations would I make another class what would have all this content in? Or maybe in the view models?

回答1:

Have you tried using the MetadataType attribute?

public class IProductMetadata
{         
    [HiddenInput(DisplayValue = false)]
    int ProductID;

    [Required(ErrorMessage = "Please enter a product name")]         
    string Name;

    [Required(ErrorMessage = "Please enter a description")]         
    string Description;
    // etc
}

[MetadataType(typeof(IProductMetadata))]
public partial class Product
{
}

I use this to attach attributes to properties on generated code through the partial class. It works really well!



回答2:

I do it on the view model and use AutoMapper to map between data object and the view model.