Adding Validation Attributes With an Entity Framework Data Model

前端 未结 5 1738
春和景丽
春和景丽 2020-11-30 03:06

Preface Feb 2015 If you are still using Entity Framework EDMX, please do yourself a favor and checkout using Entity Framework Code First instead. The differ

5条回答
  •  半阙折子戏
    2020-11-30 03:46

    You can create a partial class, separate from the EF generated class, to store the metadata in.

    //Contact.cs - The original auto-generated file 
    [System.ComponentModel.DataAnnotations.MetadataType(typeof(ContactMetadata))]
    public partial class Contact
    {
        public int ContactID { get; set; }
        public string ContactName { get; set; }
        public string ContactCell { get; set; }
    }
    
    //ContactMetadata.cs - New, seperate class
    
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    internal sealed class ContactMetadata
    {
        [Required(ErrorMessage = "Name is required.")]
        [StringLength(5)]  
        public string ContactName;
    }
    

提交回复
热议问题