I’m designing a database to hold my domain objects. I have various validation rules on the objects such as string length and if it must be filled. These things are checked in the C# code.
Does it make sense to duplicate this rules in the database, such as setting nvarchar(150) instead of nvarchar(max) and setting nullable to false for fields I know must be entered?
I don’t think so, because the data should already be validated when storing them in the database and changes to the requirements must be maintained two places instead of just one.
Please share your thoughts.
Definitely set your data types correctly — nullable, size, etc are all worth setting, because they’ll ensure your data really is right and may be more efficient. It’s a fairly ‘cheap’ thing to do, too; it doen’t take any more effort to write
varchar(150)orvarchar(max)Generating more complex rules — that a string must match a regex, or that a number has to be in a certain range — might not be worth it, unless you can generate your c# validation functions and the table constraints from a single source description, like Microsoft Oslo. The benefit of having a single system is that you can possibly generate validation at all levels; in a database, in C# server code, and in Javascript web client code, if necessary. That’s only going to pay off on complex databases, though.