Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dapper Correct Object / Aggregate Mapping

Tags:

dapper

I have recently started evaluating Dapper as a potential replacement for EF, since I was not too pleased with the SQL that was being generated and wanted more control over it. I have a question regarding mapping a complex object in my domain model. Let's say I have an object called Provider, Provider can contain several properties of type IEnumerable that should only be accessed by going through the parent provider object (i.e. aggregate root). I have seen similar posts that have explained using the QueryMultiple and a Map extension method but was wondering how if I wanted to write a method that would bring back the entire object graph eager loaded, if Dapper would be able to do this in one fell swoop or if it needed to be done piece-meal. As an example lets say that my object looked something like the following:

public AggregateRoot
      {
           public int Id {get;set;}
           ...//simple properties
           public IEnumerable<Foo> Foos
           public IEnumerable<Bar> Bars
           public IEnumerable<FooBar> FooBars
           public SomeOtherEntity Entity
           ...
      }

Is there a straightforward way of populating the entire object graph using Dapper?

like image 309
mreyeros Avatar asked Aug 29 '11 22:08

mreyeros


1 Answers

I have a similar situation. I made my sql return flat, so that all the sub objects come back. Then I use the Query<> to map the full set. I'm not sure how big your sets are.

So something like this:

var cnn =  sqlconnection();

var results = cnn.Query<AggregateRoot,Foo,Bars,FooBar,someOtherEntity,AggregateRoot>("sqlsomething"
                (ar,f,b,fb,soe)=>{
                    ar.Foo = f;
                    ar.Bars = b;
                    ar.FooBar = fb;
                    ar.someotherentity = soe;
                    return ar;

                },.....,spliton:"").FirstOrDefault();

So the last object in the Query tag is the return object. For the SplitOn, you have to think of the return as a flat array that the mapping will run though. You would pick the first return value for each new object so that the new mapping would start there.

example:

select ID,fooid, foo1,foo2,BarName,barsomething,foobarid foobaritem1,foobaritem2 from blah

The spliton would be "ID,fooid,BarName,foobarid". As it ran over the return set, it will map the properties that it can find in each object.

I hope that this helps, and that your return set is not too big to return flat.

like image 86
Omnia9 Avatar answered Sep 29 '22 11:09

Omnia9