4

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 ?

0

1 Answer 1

2

Generally speaking, your database is going to assign the ID on an insert operation, not you. If you fail to provide the ID for an read, edit or delete operation, the operation will simply not work. In other words, the database is performing the validation on the ID, not your DTO class.

Often, DTO classes are populated by some automated process, either by reading from a database, binding to a web form, or deserialization. All of the fields are populated simultaneously. There's no way to tell, ahead of time, whether the ID is going to be populated properly. That's why the validation is done after the fact.

2
  • Yeah, that's fine.. I just dislike the fact that the ID, and all other properties are now a fully public (rw), and anyone can change them. I guess, it'd be nice to give a write permission for some properties to a specific class only.. which a) can't be done, b) may not be a really great idea after all (just a gut feeling).
    – Evgeni
    Apr 13, 2012 at 16:12
  • 1
    But it is just a DTO class, after all. If the mutability really bothers you, pass the DTO class to the constructor of another class that you can control, or add a Business Logic Layer to abstract out the DTO's. Apr 13, 2012 at 16:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.