简体   繁体   中英

NullableAttribute or equivalent in Asp.net

I have a class whose properties are populated from columns in a Sql Server table. Some of the columns allow null, others do not. For numeric (tinyint, int, datetime, etc) columns, this translates to declaring the properties as Nullable<T> . For example:

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

Now, say you have a string property pulling from a character column. Obviously, since strings are classes, there is no way to define the property itself as nullable or non-nullable. However, I would still like a way to decorate the property to let programs such as custom Data-Bound controls know that it is non-nullable.

Something like this:

[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; }
}

Now, I'm a big fan of using classes that are built in to the .NET framework rather than building my own. Does anyone know of something like this?

I found AllowNullAttribute but this doesn't seem useful for disallowing null.

Another possibility is using the RequiredAttribute , and setting AllowEmptyString = false

Just curious if anyone has come across something like a NullableAttribute .

I believe RequiredAttribute from System.ComponentModel.DataAnnotations is specifically for MVC form validation (data model attribute).

The AllowNullAttribute is specifically for powershell (and does not work for strings)

Because nullable attributes are used validation there is no 1-stop attribute for it, every validation framework seems to invent their own attributes.

You could check out StringLengthAttribute from System.ComponentModel.DataAnnotations example

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM