Associate attribute with code generated property in .net

后端 未结 4 502
遥遥无期
遥遥无期 2020-12-28 08:28

I wish to set an attribute on a public property in .NET, however I do not have access to the explicit property itself, as this has been code generated in another file.

4条回答
  •  攒了一身酷
    2020-12-28 09:02

    Another option is to wrap the properties inside non-generated properties in the same class. Not ideal because you may end up having double properties but if you can make your generator make protected properties it'd be a pretty good approach.

    Just had to deal with this problem: Entity Framework generates classes, I want to serialize them to JSON with simpler names.

    // GENERATED BY EF
    public partial class ti_Users
    {
        public ti_Users()
        {
            this.ti_CardData = new HashSet();
            this.ti_Orders = new HashSet();
        }
    
        protected int userId { get; set; }
        protected string userName { get; set; }
        protected string userEmail { get; set; }
        protected string userPassHash { get; set; }
        protected Nullable userLastLogin { get; set; }
        protected string userLastIP { get; set; } 
    
        public virtual ICollection ti_CardData { get; set; }
        public virtual ICollection ti_Orders { get; set; }
    }
    

    and the add-on class:

    [JsonObject(memberSerialization: MemberSerialization.OptIn)]
    public partial class ti_Users
    {
        [JsonProperty]
        public int UserId
        {
            get { return this.userId; }
            set { this.userId = value; }
        }
    
        [JsonProperty]
        public string Name
        {
            get { return this.userName; }
            set { this.userName = value; }
        }
    
        [JsonProperty]
        public string Email
        {
            get { return this.userEmail; }
            set { this.userEmail = value; }
        }
    
        [JsonProperty]
        public string PassHash
        {
            get { return this.userPassHash; }
            set { this.userPassHash = value; }
        }
    } 
    

提交回复
热议问题