C# enum values are not limited to only values listed in it\'s definition and may store any value of it\'s base type. If base type is not defined than Int32
or s
There's EnumDataType in .NET4+ ...
Make sure you set the 3rd parameter, validateAllProperties=true
in the call to ValidateObject
so from your example:
public class Entity
{
[EnumDataType(typeof(MyEnum))]
public MyEnum EnumValue { get; set; }
}
[Fact]
public void TestInvalidEnumValue()
{
Entity entity = new Entity { EnumValue = (MyEnum)(-126) };
// -126 is stored in the entity.EnumValue property
Assert.Throws(() =>
Validator.ValidateObject(entity, new ValidationContext(entity, null, null), true));
}