How do you include an object that has a generic list property and a reference type property in dapper?

c# dapper dapper-extensions

Question

my class is:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Address> Addresses { get; set; }
    public BankAccount Account { get; set; }
}

public class Address
{
     public string Street { get; set; }
     public string City { get; set; }
     public string Zipcode { get; set; }
} 

public class BankAccount
{
      public decimal Balance {get; set;} 
      public DateTime LastDateWithdrawn { get; set;}
}

its not possible with multimapping or the multiple results i already tried. How do you do that in dapper? what I want to achieve is not to make roundtrips to the database getting the addresses and the bank account if I could use multi-mapping or multiple result or any other options.

Accepted Answer

By read your comment, i have tried to give you answer.

Let say here you have one SP.

Create PROCEDURE [dbo].[GetPersonDetail]
(
    @PersonId int
)
AS  
SET NOCOUNT ON
BEGIN

    -- 1). Get Person detail
    Select * from PersonMaster Where PersonId = @PersonId


    -- 2). Get Person Addrss
    Select * from PersonAddress Where PersonId = @PersonId

    -- 1). Get Person BankAccount
    Select * from BankAccount Where PersonId = @PersonId

End

and here is your dapper method which uses QueryMultiple method of Dapper.

public Person GetPersonDetail(int PersonId)
{
    try
    {
        var oPara = new DynamicParameters();
        oPara.Add("@PersonId", PersonId, dbType: DbType.Int);

        var person = new Person();
        using (var multiResults = _connection.QueryMultiple(GetPersonDetail, oPara, commandType: CommandType.StoredProcedure))
        {
            person.Person = multiResults.Read<Person>().FirstOrDefault();
            person.Addresses = multiResults.Read<Address>();
            person.BankAccount = multiResults.Read<BankAccount>().FirstOrDefault();
        }
        return person;
    }
    catch (Exception ex)
    {
        thow;
    }
}

Hope this may help you... All the best.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why