Smith Waliko Msiska
Smith Waliko Msiska

Reputation: 101

Dapper Multi Mapping stops at 3rd lavel nesting

I have taken a question and modified it to form my question. I have a query that is mapping correctly from the initial class, to the second class and elements attached to the second class (3rd) but not elements attached to the 3rd class. an example as follows.

public class Part {

 public int Id { get; set; }
  public string Name { get; set; }

  public Address Address { get; set; }
}

public class Address {
  public int Id { get; set; }
  public string Street { get; set; }

  public SiteOu Ou { get; set; }
}

public class SiteOu {
  public int Id { get; set; }

  public SiteOuName SiteOuN { get; set; }
}

public class SiteOuName
{
public int Id { get; set; }
  public string Name { get; set; }
}

Dapper:

public void TestSplitOn()
{
    var conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Integrated Security=true;Initial Catalog=db");
    conn.Open();
    const string sql = "select Id = 1, Name = 'My Part', " +
                       "Id = 2, Street = 'My Street', " +
                       "Id = 1, SiteOuNameId = '1'" +
                       "Id = 1, Name = 'My Site', " +;
    var result = conn.Query<Part, Address, SiteOu, SiteOuName, Part>(sql, (part, address, siteOu, siteOuName) =>
    {
        part.Address = address;
        address.Ou = siteOu;
        SiteOu.SiteOuName = siteOuName
        return part;
    },
    commandType: CommandType.Text
    ).FirstOrDefault();
}

If I remove SiteOuName from the Dapper mapping, the code works but doesn't map the SiteOuName object, but when I leave it as it is, it shows me that the address object reference is null.

Upvotes: 0

Views: 105

Answers (1)

Yepo
Yepo

Reputation: 134

As far as I can see there are couple of issues in your Dapper code. Firstly, your query should be like;

const string sql = "select Id = 1, Name = 'My Part', " +
                           "Id = 2, Street = 'My Street', " +
                           "Id = 1, SiteOuNameId = '1'," +
                           "Id = 1, Name = 'My Site'";

You are missing a comma next to the SiteOuNameId = '1' and you have extra comma and '+' sign next to Name = 'My Site'

Secondly, your mapping is wrong, it should be like

part.Address = address;
address.Ou = siteOu;
siteOu.SiteOuN = siteOuName;
return part;

In your code, S is upper case which makes complier think you are using the SiteOu class. Also, SiteOu class doesn't have a property named SiteOuName, it should be SiteOuN.

Upvotes: 1

Related Questions