1

At the moment I am writing my own ValidationAttribute for my mvc application.

I have following ValidationAttribute code.

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Class | AttributeTargets.Parameter, AllowMultiple = false)] 
public class RecordAttribute: ValidationAttribute
{

   public UniqueDataRecordAttribute(string primaryKeyProperty)
   {

   }
}

I pass the field name of my primary property as a string to my attribute and make sone validation. E.g.:

[RecordAttribute("CustomerID")]
public class CustomerMetaData
{


}

This works for me, but I will run into problems if the name of the primary key will change.

I created a enum which contains the primary key attribute. But when I try to pass it the compiler is telling me:

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

I also tried this approach: Associating enums with strings in C# but the effect is the same.

Is there any chance to pass a enum (or other compiled value) to my attribute?

Thank you

Community
  • 1
  • 1
Peter Hubert
  • 95
  • 1
  • 11

1 Answers1

0

Are you trying to do something like this?

[RecordAttribute(Keys.CustomerID.ToString())] 
public class CustomerMetaData 
{ 
}

That won't work because the string returned by Keys.CustomerID.ToString() isn't a constant.

Instead of an enum could you use a static class of const string fields?

static class Keys {
  public const string CustomerID = "CustomerID";
}

Then this will work:

[RecordAttribute(Keys.CustomerID)] 
public class CustomerMetaData 
{ 
}
Andrew Kennan
  • 13,947
  • 3
  • 24
  • 33