3

我无法使用查询构建复杂的对象。我怎样做?

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

4 回答 4

1

如您之前所写,使用Join Method 与“Contact”表连接,

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();
于 2018-08-27T13:13:08.927 回答
1

我的代码:

        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>();
于 2018-08-24T14:14:12.200 回答
0

您可以使用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"));
        }
    }

您也可以使用“.QueryMultiple”。阅读 Dapper 的文档,或查看单元测试以获取更多示例。

于 2018-08-24T14:01:27.743 回答
0

您可以结合使用 SqlKata(@amd 的回答)和 Dapper(@Void Ray 的回答):

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);
于 2022-01-13T01:41:58.963 回答