Home > Mobile >  Set Data Annotation MaxLength w/ Variable?
Set Data Annotation MaxLength w/ Variable?

Time:11-15

I want to set the [MaxLength()] data annotation in my EF Core 7 entity with a variable. Here's my code.

    public static class Constants
    {
        public static byte IdentifierMaxLength { get { return 46; } }
        public static byte NameMaxLength { get { return 64; } }
        public static ushort DescriptionMaxLength { get { return 1024; } }
        public static ushort UsageMaxLength { get { return 1024; } }
    }

    public class TagEntity
    {
        private byte _maxIdentifierLength;

        public Tag()
        {
            _maxIdentifierLength = Constants.IdentifierMaxLength;
        }

        [Required]
        [MaxLength(_maxIdentifierLength)]
        public string Identifier { get; set; }
    }
    
    // Or better yet:
    [MaxLength(Constants.IdentifierMaxLength)]

I get this error instead:

An object reference is required for the non-static field, method, or property 'Tag._maxIdentifierLength'

Is this possible? If not, is there another way to go about this so I don't have to change these lengths in multiple places if they ever need to change?

CodePudding user response:

Values provided to Attributes must be known at compile time. Constants are a good way of providing that guarantee.

Change your Constants class to have actual constants. In addition, you'll need/want to change the type to int to match the parameter for the attribute.

public static class Constants
{
    public const int IdentifierMaxLength = 46;
}

Now you can do

[MaxLength(Constants.IdentifierMaxLength)]
  • Related