3

I cant built a complex object with a query. How I do?

public class Person
{
    public long Id { get; set; }
    public string Name { get; set; }
    public Contact Contact { get; set; }
}

public class Contact
{
    public long Id { get; set; }
    public string FoneNumber { get; set; }
}
VFB
  • 41
  • 1
  • 4

4 Answers4

1

My code:

        var compiler = new SqlServerCompiler();
        var db = new QueryFactory(connection, compiler);

        var person = db.Query("Person")
                        .Select("Person.Id", "Person.Name", "Contact.Id", "Contact.FoneNumber")
                        .Join("Contact", "Person.Id", "Contact.PersonId")
                        .Where("Person.Id", 1)
                        .FirstOrDefault<Person>();
VFB
  • 41
  • 1
  • 4
1

As you have wrote before, use the Join Method to join with the "Contact" table,

var row = db.Query("Person")
            .Select(
                "Person.Id",
                "Person.Name",
                "Contact.Id as ContactId",
                "Contact.FoneNumber as FoneNumber"
            )
            .Join("Contact", "Person.Id", "Contact.PersonId")
            .Where("Person.Id", 1)
            .FirstOrDefault();
amd
  • 20,637
  • 6
  • 49
  • 67
0

You can use "Multi-Mapping" feature of Dapper.

    [Test]
    public void Test_Multi_Mapping()
    {
        using (var conn = new SqlConnection(@"Data Source=.\sqlexpress; Integrated Security=true; Initial Catalog=test"))
        {
            var result = conn.Query<Person, Contact, Person>(
                "select Id = 1, Name = 'Jane Doe', Id = 2, FoneNumber = '800-123-4567'",
                (person, contact) => { person.Contact = contact;
                    return person;
                }).First();

            Assert.That(result.Contact.FoneNumber, Is.EqualTo("800-123-4567"));
        }
    }

You can also use ".QueryMultiple". Read Dapper's documentation, or take a look at the unit tests for more examples.

Void Ray
  • 9,849
  • 4
  • 33
  • 53
0

You can use a combination of SqlKata (@amd's answer) and Dapper (@Void Ray's answer):

var query = new SqlKata.Query(...);      //compose your sqlkata query as user amd indicated above
var compiler = new PostgresCompiler();   //or mssqlcompiler or whatever
var compiled = compiler.Compile(query);
var sql = compiled.Sql;
var parameters = new DynamicParameters(compiled.NamedBindings);
var result = await db.QueryAsync<Person, Contact,Person>(sql,(p,c)=>{p.Contact = c;  return p;},parameters);
BlackjacketMack
  • 5,472
  • 28
  • 32