Dapper and Data Type Conversions.

Ronald Rex 1,526 Reputation points
2023-11-20T23:09:06.6966667+00:00

Hi Friends. I was wondering whats the most efficient way to convert from one Data Type to another while working with Dapper Objects. I keep getting this compile error Cannot implicitly convert type Datapacketpayer[]to DatapackePayerPayee[]. Thanks !!!

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
9,428 questions
{count} votes

Accepted answer
  1. Karen Payne MVP 34,576 Reputation points
    2023-11-21T14:40:10.82+00:00

    Usually with Dapper two classes (and in your case I may get this wrong as I not sure how the relations are setup in the database) the query uses a join, then for Dapper see spliton.

    Example

    I have a contact model and a ContactDevices model, to get data the SELECT statement. In my case I created the models using a tool.

    SELECT C.ContactId,
           C.FirstName,
           C.LastName,
           C.ContactTypeIdentifier,
           CT.ContactTitle,
           CD.id AS DeviceId,
           CD.ContactId,
           CD.PhoneTypeIdentifier,
           CD.PhoneNumber,
           CT.ContactTypeIdentifier
    FROM dbo.Contacts AS C
        INNER JOIN dbo.ContactType AS CT
            ON C.ContactTypeIdentifier = CT.ContactTypeIdentifier
        INNER JOIN dbo.ContactDevices AS CD
            ON C.ContactId = CD.ContactId;;
    

    Then in code (SQL.ContactsWithDevices points to the statement above) we get each contact with one or more contact devices. My code is a tad more complex e.g. there is more to contact devices e.g. types of devices and locations.

    public static async Task<List<Contacts>> GetContactsAndDevices()
    {
        await using SqlConnection cn = new(ConnectionString());
    
        var list = cn.Query<Contacts, ContactDevices, Contacts>(
            SQL.ContactsWithDevices(), (contact,  contactDevices) =>
            {
    
                contact.ContactDevices.Add(contactDevices);
                return contact;
            }, splitOn: "ContactId,DeviceId");
    
    
        return list.ToList();
    }
    

0 additional answers

Sort by: Most helpful