How to add data annotation for entities automatically created by Data-First?

前端 未结 3 1528
-上瘾入骨i
-上瘾入骨i 2020-12-28 23:53

If model-first, we use [MetadataType(typeof(ConceptMetadataSource))] to attach a MetadataSource file which contains all the data annotations like [Hidden

3条回答
  •  难免孤独
    2020-12-29 00:19

    All you have to do is create another partial class and use metadatatype attribute. Here is the sample code

    //This is generated by EDMX
    
    namespace DataLayer
    {
        using System;
        using System.Collections.Generic;
    
        public partial class Customer
        {
            public Customer()
            {
                this.CustomerAddresses = new HashSet();
                this.CustomerOrders = new HashSet();
            }
    
            public int Id { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string EmailId { get; set; }
    
    
            public Nullable DateOfBirth { get; set; }
    
            public virtual ICollection CustomerAddresses { get; set; }
            public virtual ICollection CustomerOrders { get; set; }
        }
    }
    

    Add following code manually

    namespace DataLayer
    {
        [MetadataType(typeof(CustomerMetaData))]
        public partial  class Customer
        {
    
        }
        public class CustomerMetaData
        {
            [StringLength(10, ErrorMessage = "First name must be 25 characters or less in length.")]
            [Required(ErrorMessage = "First name is required.")]
            public String FirstName { get; set; }
        }
    }
    

提交回复
热议问题