Dapper and object validation/business rules enforcement
Posted
by
Eugene
on Programmers
See other posts from Programmers
or by Eugene
Published on 2012-04-13T14:34:04Z
Indexed on
2012/04/13
17:42 UTC
Read the original article
Hit count: 428
design-patterns
|validation
This isn't really Dapper-specific, actually, as it relates to any XML-serializeable object.. but it came up when I was storing an object using Dapper.
Anyways, say I have a user class. Normally, I'd do something like this:
class User
{
public string SIN {get; private set;}
public string DisplayName {get;set;}
public User(string sin)
{
if (string.IsNullOrWhiteSpace(sin))
throw new ArgumentException("SIN must be specified");
this.SIN = sin;
}
}
Since a SIN is required, I'd just create a constructor with a sin parameter, and make it read-only.
However, with a Dapper (and probably any other ORM), I need to provide a parameterless constructor, and make all properties writeable. So now I have this:
class User: IValidatableObject
{
public int Id { get; set; }
public string SIN { get; set; }
public string DisplayName { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
// implementation
}
}
This seems.. can't really pick the word, a bad smell?
A) I'm allowing to change properties that should not be changed ever after an object has been created (SIN, userid)
B) Now I have to implement IValidatableObject or something like that to test those properties before updating them to db.
So how do you go about it ?
© Programmers or respective owner