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 specifications (e.g. varchar(6)
and I'd like to validate the length of all string properties before passing them on to the stored procedures.
Is there a simple, declarative way to do this?
I have two conceptual ideas so far:
Attributes
public class MyDataClass
{
[MaxStringLength = 50]
public string CompanyName { get; set; }
}
I'm not sure what assemblies/namespaces I would need to use to implement this kind of declarative markup. I think this already exists, but I'm not sure where and if it's the best way to go.
Validation in Properties
public class MyDataClass
{
private string _CompanyName;
public string CompanyName
{
get {return _CompanyName;}
set
{
if (value.Length > 50)
throw new InvalidOperationException();
_CompanyName = value;
}
}
}
This seems like a lot of work and will really make my currently-simple classes look pretty ugly, but I suppose it will get the job done. It will also take a lot of copying and pasting to get this right.