Adding Validation Attributes With an Entity Framework Data Model

前端 未结 5 1740
春和景丽
春和景丽 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:57

    I know this has been marked answered but I want to clear some stuffs up.

    @SteveCav said: "This member is defined more than once". I had the same exact same error. Spent hours trying to figure out.

    To finally correct it, you have to create a separate file class in the same Assembly(I think this is already mentioned here). But what I want to stress is that this class should be nested with a partial class representing the Inner Class.

    And then you decorate that inner class with the Annotation class. Like this:

    //ContactMap.cs - Present in the same namespace as Contact.cs
    [System.ComponentModel.DataAnnotations.MetadataType(typeof(ContactMap))]
    partial class Contact // Present in the ContactMap class. This represent the Inner Class
    {
    }
    
    //ContactMap.cs - This represent the outer class
    
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    public class ContactMetadata
    {
        [Required(ErrorMessage = "Name is required.")]
        [StringLength(5)]  
        public string ContactName;
    }
    

    Hope this is clearer or more understandable.

提交回复
热议问题