Associate attribute with code generated property in .net

后端 未结 4 506
遥遥无期
遥遥无期 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:08

    Since the generated class is a partial class, the following should work:

    1. Create an interface that has this property declared in it, and decorate it with ValidateNonEmpty attribute.
    2. Create your own partial class with same name as the AutoGenerated class, and make this implement the interface that you just created.
    3. The property should now be decorated with that attribute

    For example:

    // Decorate the properties with attributes as required
    public interface IMyInterface
    {
        [ValidateNonEmpty("Name is required")]
        string Name { get; set; }
    }
    
    // This is the partial class I created, that implements the interface
    public partial class MyGeneratedClass : IMyInterface
    {    
    }
    
    // This is the auto-generated class
    public partial class MyGeneratedClass
    {
        public virtual string Name { get; set; }
    }
    

    I got this idea from geekswithblogs.

提交回复
热议问题