I'd like to use the StringLength Attribute on an Entity, but instead of using a literal or a constant, to use a static property.
e.g
[StringLength(MyClass.MyStaticProperty)]
public string Code { get; set; }
However this results in the following error...
An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
... has anyone got a work around or an alternative, other than using a string literal or constant?
In case you're wondering why a static property? The static property will return a value from an injected singleton. The value will be injected at startup of the application.
Thanks... and Merry Christmas...
Creating your own attribute is probably the best solution. You can then also take control over any other logic you might want to implement later.
public class CustomStringLength: ValidationAttribute
{
public CustomStringLength()
{
}
public override bool IsValid(object value)
{
return (string)value.Length == MyClass.MyStaticProperty;
}
}
Considering MyClass.MyStaticProperty is an int.
Usage:
[CustomStringLength]
public string Code { get; set; }
StringLength attribute parameter should be known at compile time.
You can either specify the exact value or refer to a constant value:
public static class MyClass
{
public const int MyStaticProperty = 5;
}
[StringLength(MyClass.MyStaticProperty)]
public string Code { get; set; }
Note that there is no static keyword, since const implies static.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With