是否有超出框验证在DataAnnotations命名空间枚举值? [英] Is there out-of-the box validator for Enum values in DataAnnotations namespace?
问题描述
C#枚举值不限于仅在它的定义中所列的值,并且可以存储任何值的它的基类型。如果基本类型不大于的Int32
定义,或者干脆 INT
被使用。
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 simply int
is used.
我开发一个WCF serivice这就需要有信心,一些枚举具有分配一个值,而不是默认值,我开始与单元测试,以找出是否 [必需]
将在这里做正确的工作。
I am developing a WCF serivice which needs to be confident that some enum has a value assigned as opposed to the default value for all enums of 0. I start with a unit test to find out whether [Required]
would do right job here.
using System.ComponentModel.DataAnnotations;
using Xunit;
public enum MyEnum
{
// I always start from 1 in order to distinct first value from the default value
First = 1,
Second,
}
public class Entity
{
[Required]
public MyEnum EnumValue { get; set; }
}
public class EntityValidationTests
{
[Fact]
public void TestValidEnumValue()
{
Entity entity = new Entity { EnumValue = MyEnum.First };
Validator.ValidateObject(entity, new ValidationContext(entity, null, null));
}
[Fact]
public void TestInvalidEnumValue()
{
Entity entity = new Entity { EnumValue = (MyEnum)(-126) };
// -126 is stored in the entity.EnumValue property
Assert.Throws<ValidationException>(() =>
Validator.ValidateObject(entity, new ValidationContext(entity, null, null)));
}
}
这不,第二次测试不抛出任何。例外
It does not, the second test does not throw any exception.
我的问题是:是否有一个验证器属性检查提供的值在 Enum.GetValues
?
My question is: is there a validator attribute to check that supplied value is in Enum.GetValues
?
更新即可。
确保使用 ValidateObject(对象,ValidationContext,布尔)
与去年参数等于真
代替的 ValidateObject(对象,ValidationContext)
在我的单元测试完成。
Update.
Make sure to use the ValidateObject(Object, ValidationContext, Boolean)
with last parameter equal to True
instead of ValidateObject(Object, ValidationContext)
as done in my unit test.
推荐答案
有的 EnumDataType 英寸NET4 + ...
There's EnumDataType in .NET4+ ...
请确保您呼叫的第三个参数, validateAllProperties = TRUE
设置为 ValidateObject
Make sure you set the 3rd parameter, validateAllProperties=true
in the call to ValidateObject
所以从你的例子:
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<ValidationException>(() =>
Validator.ValidateObject(entity, new ValidationContext(entity, null, null), true));
}
这篇关于是否有超出框验证在DataAnnotations命名空间枚举值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!