将行拆分为多个嵌套对象

时间:2017-12-14 17:17:01

标签: dapper

我收到了以下问题:

select id, name, email, supervisor, createdBy, createdAt, changedBy, changedAt from XXX

现在,我想将每一行映射到看起来像这样的东西:

public class Organisation{
  public int Id{get; set; }
  public string Name{get; set; }
  public ContactInfo Contact{get;set;}
  public Action CreatedBy{get;set;}
  public Action ChangedBy{get;set;}
}
public class ContactInfo{
  public string Name{get;set;}
  public string Email{get;set;}
}
public class Action{
  public string Username{get;set;}
  public DateTime At{get;set;}
}

我已经看到了一些显示如何对信息进行分区的示例,但在这个示例中似乎不起作用。它可以完成,还是应该将我的查询映射到一个辅助对象,然后将其映射到这些类中?

感谢。

路易斯

1 个答案:

答案 0 :(得分:1)

  

Dapper允许您将单行映射到多个对象。这是一个   关键功能,如果你想避免无关的查询和急切负载   关联。

您可以阅读更多here

以下是一个例子:

[Test]
public void Test_Multi()
{
    using (var conn = new SqlConnection(@"Data Source=.\sqlexpress;Integrated Security=true; Initial Catalog=foo"))
    {
        var result = conn.Query<Organisation, ContactInfo, Action, Action, Organisation>(
            @"select Id = 100, Name = 'Foo', 
                Name = 'Contact Name', Email = 'contact@foo.com', 
                Username = 'The Creator', At = '12/25/2017', 
                Username = 'The Modifier', At = '12/26/2017' ",
            (org, contact, cretedBy, changedBy) =>
            {
                org.Contact = contact;
                org.CreatedBy = cretedBy;
                org.ChangedBy = changedBy;

                return org;
            }, splitOn: "Id, Name, Username, Username").First();

        Assert.That(result.Id, Is.EqualTo(100));
        Assert.That(result.Contact.Email, Is.EqualTo("contact@foo.com"));
        Assert.That(result.CreatedBy.Username, Is.EqualTo("The Creator"));
        Assert.That(result.ChangedBy.Username, Is.EqualTo("The Modifier"));

    }
}