Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Provide Dapper with a class instance to map to instead of always instantiating a new one?

Tags:

c#

.net

orm

dapper

I've looked through the source and I'm not finding anything (although I'm not great at IL), but I would like see if there is a way to provide Dapper a class instance instead of it always instantiating a new one. The reason for this is we may sometimes make two separate calls to two different stored procedures - one returns some columns of an 'entity', the other returns other columns. However, instead of the second query using the entity we received in the first call, we instead get two instances of essentially the same entity. It would be much more preferable for Dapper to use the existing entity class and map the query results to that existing class.

Is there any way to intercept Dapper's class instantiation so as to provide it with an existing instance if needed?

like image 702
Amberite Avatar asked Nov 09 '22 16:11

Amberite


1 Answers

Excellent question. At the moment, it allows you to indicate a particular constructor, but it always news:

 il.Emit(OpCodes.Newobj, specializedConstructor);

What we could do is make it possible to specify either a constructor or a static factory method; I suspect this would be just a three-line change to the core materializer code, plus a few other places. Not impossible, but then it gets into questions like calling-context: how does dapper provide caller-specified context to the factory. Again: all possible (protobuf-net does pretty much the same thing).

But none of that exists today. It wouldn't be impossible.

like image 135
Marc Gravell Avatar answered Nov 14 '22 22:11

Marc Gravell