开发者

DataAnnotations WriteOnly if property == null

I have the following property:

开发者_高级运维
public virtual String Firstname { get; set; }

and i only want to be able to write to the field IF it is currently null (not set), it this possible to achieve through DataAnnotations?


Data annotations are metadata used for example for validation so you can create custom data annotation to validate property value but the validation cannot ensure that your property will not be set if it already has value. That is code which should be part of property's setter itself like:

private string _firstName;

public string FirstName
{
    get 
    {
        return _firstName;
    }
    set
    {
        if (_firstName != null) throw ...
        _firstName = value;
    }
}

If by data annotations you simply mean attributes then the answer is: It can be achieved with attributes BUT you need something which will implement some logic related to the attribute. This is usually done through Aspect oriented programming (AOP) where you will create marker attribute which will be used by some complex API. The API will based on that attribute wrap your class with custom code adding the if statement either at compile time (for example PostSharp) or at runtime (for example Unity, Spring.NET).


Another way to achive this, by me more elegant, do not implement set for the property, but only get

private string _firstName;

public string FirstName
{
    get 
    {
        return _firstName;
    }

}

and have a function:

public void SetFirstName(string FirstName) 
{
   _firstName = FirstName;
}

So no exception, no return value handling. You have one property the only retrieve value, and one function, or constructor (why not, depends on your architecture, it's hard to deduct from post) that initialized it only once.

By me the API of your object will be more clear and straightforward in this way.

Regards.


There is also a specific DataAnnotation syntax to achieve this:

[DisplayFormat(NullDisplayText = "some string")]
public virtual String Firstname { get; set; }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜