用sqlkata查询复杂对象

时间:2018-08-24 13:21:18

标签: dapper sqlkata

我无法使用查询构建复杂的对象。我该怎么办?

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; }
}

3 个答案:

答案 0 :(得分:1)

如您之前所写,请使用Join方法与“联系”表连接,

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();

答案 1 :(得分:0)

您可以使用Dapper的“ Multi-Mapping”功能。

    [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"));
        }
    }

您还可以使用“ .QueryMultiple”。阅读Dapper的文档,或查看unit tests以获得更多示例。

答案 2 :(得分:0)

我的代码:

        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>();