1

What's the best way to do the following...

conn.Query<Foo>(@"SELECT 1, 2, 'ZEBRA'");

Say Foo has a constructor like so...

public Foo(Bar test, string zebra)

..And Bar has a constructor like this:

public Bar(int one, int two)

This doesn't work, what would be the best approach to achieve the desired result.

Dog Ears
  • 9,637
  • 5
  • 37
  • 54
  • `Foo(int first, int second, string derp) : this(new Bar(first, second), derp){}` –  Jun 13 '17 at 13:15

2 Answers2

2

You could try non-generic Query API (more details are here https://stackoverflow.com/a/8995135/229949):

conn.Query(@"SELECT 1 as one, 2 as two, 'ZEBRA' as zebra")
  .Select(_ => new Foo(new Bar(_.one, _.two), _.zebra);
the_joric
  • 11,986
  • 6
  • 36
  • 57
2

Don't try to hydrate into your real models directly from Dapper if they have constructor requirements like that. Instead, hydrate into a private/internal class, and then instantiate and return the proper models.

internal class FooBarQueryModel 
{
    public string Zebra { get; set; }
    public int One { get; set; }
    public int Two { get; set; }
}

conn.Query<FooBarQueryModel>(sql).Select(qm => new Foo(new Bar(qm.One, qm.Two), qm.Zebra));
Graham
  • 3,217
  • 1
  • 27
  • 29