3

I'm attempting to use Dapper to return a set of Shares and an associated one-to-many collection of ShareItems and ShareHistories. My Dapper call looks like this:

string sql =
    @"select s.Id, s.UserId, s.Name, si.ShareId as Id, si.Name as ItemName
    , sh.ShareId As Id, sh.DateShared, sh.SentTo 
    from Shares s 
    inner join ShareItems si on s.Id = si.ShareId
    inner join ShareHistory sh on s.Id = sh.ShareId
    where s.Id = @shareId";

    return conn.Query<Share, List<ShareItem>, List<ShareHistory>, Share>(
                sql,
                (share, shareItems, history) => 
                    { 
                      share.Items = shareItems; 
                      share.History = history; return share; 
                    },
                new { shareId = shareId }).Single();

When I run the query in SQL I get the flattened data I expect. However, when I run the code through Dapper the Items and History collections are coming back empty. I was screwing around with the splitOn parameter but after reading this question I now understand what splitOn is doing (this would be good to have somewhere on the Dapper site btw) and I think I'm handling that part okay. So what am I doing wrong?

1
  • I've edited your code now for you. You should try to avoid getting scrollbars. It helps alot for others. And you're likely to get more answers. Commented Mar 26, 2012 at 15:01

1 Answer 1

2

I don't think you can populate a deep object graph from 1 row. (Unless all items are in that one row) There's a similar question: Populating a list in a object with dapper

Edit: There's also QueryMultiple - you might want to check that out. It allows the return of multiple resultsets. You could then map your entities.

Query Multiple Example

Sign up to request clarification or add additional context in comments.

4 Comments

Hm, that would be unfortunate. My current workaround is making a db call per collection, but I was hoping I could get this down to one database call in Dapper.
Have you checked out the QueryMultiple function? I've added an edit.
Does QueryMultiple execute as one db hit or one per select? If it's one per select, then I'm not gaining much over the original solution posted above. I did try it though and it does work.
I'll accept this as the answer since it's what I ended up using. I haven't taken the opportunity to profile and see what is going to SQL, but in the interest of avoiding premature optimization this is working flawlessly.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.