Search code examples
c#.netdatabasevalidationdata-integrity

Where is the most convenient place to validate a property length of a saveable object?


I wonder where is the most convenient place to validate a property length on a persistent object.

Let's say, there is a table called Country in my Db with CountryCode nvarvhar(3).

And I have a mapped object Country wiht property CountryCode which can be saved into Db.

Where should I check if the Country code set by user does not exceed 3 characters:

  • In the setter of property CountryCode
  • OR at the time of saving into Db

Can you please advice?

Thanks


Solution

  • I've found that it is easiest to allow properties to be set to any value (of the correct data type anyway) and then validate it before saving it.

    I like to use the validation attributes built into .Net. This keeps the logic associated with the property. There is a StringLengthAttribute class that should do the trick for what you are asking for.

    The attributes are in the System.ComponentModel.DataAnnotations namespace (you'll need to reference the assembly of the same name).

    MVC and EntityFramework have a built in way to validate the data. If you need to perform the logic yourself, here is some code that might help you get started...

    var ctx = new ValidationContext(obj, null, null);
    Validator.ValidateObject(obj, ctx);