What ways can I ensure that a string property is of a particular length?

前端 未结 5 1620
北海茫月
北海茫月 2020-12-18 17:31

I\'ve created some classes that will be used to provide data to stored procedures in my database. The varchar parameters in the stored procs have length specif

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-18 17:51

    The first method using attribute sounds good.

    Implement your attribute by inherit from the System.Attribute class and mark your class with AttributeUsage attribute to let your attribute being set on a field.

    Then, using reflection, check for presence and value of the attribute before sending the value to the SP.

    Thats provide you with lot more flexibility than the second method. If tomorow you decide to let your SP receive the first N chars of a too lengthly string, you won't have to modify all your code but only the one that interpret the attribute.

    There are indeed some validation attribute in the framework but I wouldn't use those one because you could implies some behaviour you don't expect and because you won't be able to modify then in any way (liek if you want something like [MaxLength(50, true)] to specify that using the first 5O chars is OK.

提交回复
热议问题