Guybrush Threepwood
Guybrush Threepwood

Reputation: 1266

How to add a new PropertyType in Dapper .Query<>()

I have a C# Class called Person and within that class, the Person has a Telephone property of type TelephoneDetails.

I am trying to Query a Database using Dapper and within my Query, I need to retrieve the current telephone number (known as Detail) and put it into my Telephone property.

Here's what I've tried:

    var person = _connection.Query<Person>($"SELECT person AS Person, Detail AS {new TelephoneDetails{Telephone = ""}} " + // Here's my issue
                                                                  "FROM dbo.Foo WHERE PersonId = @id",
                                                                  new {id}).FirstOrDefault();

    return person;

Every time I return the local variable person I return a null value in my Telephone Property. How do I take the data from the database instantiate the property?

I feel I have given everything needed but if not please use the comments section for clarification.

Thanks in advance.

Upvotes: 2

Views: 624

Answers (1)

Guybrush Threepwood
Guybrush Threepwood

Reputation: 1266

The answer is a collection of both @Markeli and @Flydog57 comments

I solved the question by creating a new class with string property types for both datasets that I was wanting in return (Person and Telephone). What's important to note is that Dapper uses a systematic approach, so your first type in the recordset <TFirst> should match what you're retrieving first (Person) which should follow throughout in this order.

public Person GetPersonDetails(int id)
{
    var person= _connection.Query<Person, TelephoneDetails, PersonDetailsRoot>(
        "SELECT p.* "/* TFirst */", td.* " +
        "FROM Person p " +
        "INNER JOIN TelephoneDetails td ON p.PersonContactId = td.ContactId " +
        "WHERE Id = @id",
        (person /* This is first to match the TFirst*/, details) => new PersonDetailsRoot // The new class made
        {
            PersonName = person.Adviser,
            TelephoneNumber = detail.Detail
        },
        new {id},
        splitOn: "ContactId"
    ).ToList();

    if (!person.Any())
    {
        return null;
    }

    return new PersonDetails();

Upvotes: 2

Related Questions