Dapper does not warn or fails with missing data

Let's say I have a class (for example, a simplified one), and I want to make sure that the PersonId and Name field is ALWAYS filled.

public class Person { int PersonId { get; set; } string Name { get; set; } string Address { get; set; } } 

Currently, my request will be

 Person p = conn.Query<Person>("SELECT * FROM People"); 

However, I may have changed my database schema from PersonId to PID, and now the code will work very well.

What I would like to do is one of the following:

  • Decorate the PersonId property with an attribute such as Required (this dapper can check)

  • Tell dapper to find out that the mappings do not populate completely (i.e. an exception if all the properties in the class are not populated with data from the request.)

Is this currently possible? If not, can someone tell me how I can do this without affecting performance too badly?

IMHO , the second option would be better, because it does not violate the existing code for users, and it does not require any more decoration of attributes for classes that we may not have access to.

+4
source share
1 answer

This is currently not possible. Indeed, there are many cases where it is useful to actively fill in the partial model, so I would not want to add anything implicit. In many cases, the domain model is an extended representation of the data model, so I don’t think option 2 can work - and I know that it will break in gazillion places in my code; p If we restrict ourselves to more explicit parameters ...

So far, we have deliberately avoided such things as attributes; the idea was to keep it as accurate and direct as possible. I am not pathologically against attributes - simply: it can be problematic to examine them. But maybe the time has come ... we could, perhaps, at the same time allow simple column matching, i.e.

 [Map(Name = "Person Id", Required = true)] int PersonId { get; set; } 

where both Name and Required are optional. Thoughts? This is a bit problematic, although, in particular, at the moment we are only exploring the columns that we can see, in particular, in the extensibility API.

Another possibility is the interface that we check, allowing you to manually check the data after loading; eg:

 public class Person : IMapCallback { void IMapCallback.BeforePopulate() {} void IMapCallback.AfterPopulate() { if(PersonId == 0) throw new InvalidOperationException("PersonId not populated"); } } 

The interface option makes me happier in many ways:

  • he avoids a lot of additional reflective sounding (just one check)
  • it is more flexible - you can choose what is important to you.
  • this does not affect the extensibility API

but: it is more tame.

I am open to input, but I want to make sure that we can handle this, and not in a hurry with all the machine guns.

+5
source

All Articles