Asp.net中的NullableAttribute或等价物

时间:2016-06-02 17:02:22

标签: c# asp.net .net

我有一个类,其属性从Sql Server表中的列填充。有些列允许null,有些则不允许。对于数字(tinyint,int,datetime等)列,这转换为将属性声明为Nullable<T>。例如:

public class MyClass
{
    public int MyNonNullableColumnProperty { get; set; }
    public int? MyNullableColumnProperty { get; set; }
}

现在,假设您从字符列中提取字符串属性。显然,由于字符串是类,因此无法将属性本身定义为可空或不可空。但是,我仍然想要一种装饰属性的方法,让自定义数据绑定控件等程序知道它是不可为空的。

这样的事情:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
public class NullableAttribute : Attribute
{
    public NullableAttribute(bool nullable)
    {
        Nullable = nullable;
    }
    public bool Nullable { get; private set; }
}

public class MyClass
{
    [Nullable(false)]
    public string MyNonNullableColumnProperty { get; set; }
    [Nullable(true)]
    public string MyNullableColumnProperty { get; set; }
}

现在,我非常喜欢使用内置于.NET框架中的类而不是构建自己的类。有谁知道这样的事情?

我找到了AllowNullAttribute,但这似乎不适用于禁止null。

另一种可能性是使用RequiredAttribute,并设置AllowEmptyString = false

只是好奇是否有人遇到类似NullableAttribute的内容。

1 个答案:

答案 0 :(得分:0)

我相信System.ComponentModel.DataAnnotations中的RequiredAttribute专门用于MVC表单验证(数据模型属性)。

AllowNullAttribute专门用于powershell(并不适用于字符串)

因为使用了可空属性验证,所以没有1-stop属性,每个验证框架似乎都发明了自己的属性。

你可以退房 System.ComponentModel.DataAnnotations中的StringLengthAttribute 示例

[StringLength( 300, MinimumLength = 0 )] //allows any string from empty to 300 length