开发者

Where to put data annotations tags?

开发者 https://www.devze.com 2023-02-03 17:55 出处:网络
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.

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?


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!


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

0

精彩评论

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