Insert data in child object using Dapper

dapper

Question

I have the following classes

public class TenantUser
{
    public string UserId { get; set; }
    public DateTime LastActivityDate { get; set; }
    public TenantInformation TenantInfo { get; set; }
}

public class TenantInformation
{
    public string InstitutionId { get; set; }
    public string InstitutionName { get; set; }
}

I am able to retrieve information using Dapper successfully:

string query = "select tu.UserId, tu.InstitutionId, ti.InstitutionName 
        from tenantuser as tu " 
        + "inner join tenantinfo ti on ti.InstitutionId = tu.InstitutionId";

var res = d.Query<TenantUser, TenantInformation, TenantUser>(query, (tu, ti) =>
{ tu.TenantInfo = ti; return tu; }, "InstitutionId");

How would I insert data into the TenantUser table?

I tried this:

var tenantUser = new TenantUser();
tenantUser.UserId = "testuser@mail.com";
tenantUser.TenantInfo = 
      d.Query<TenantInformation>("select * from tenantinfo").First(); //This works
tenantUser.LastActivityDate = DateTime.Now;

string query = 
    "insert into tenantUser values(@userid, @institutionid, @lastactivitydate)";
d.Execute(query, tenantUser);

Since InstitutionId is a property in the child object TenantInfo i get the error: "Must declare the scalar variable \"@institutionid\".

How would I fix this please?

Accepted Answer

Dapper is deliberately simplistic. In your scenario, you would have to flatten the data - at least for the insert:

d.Execute(query, new {
    userid = tenantUser.UserId,
    institutionid = tenantUser.TenantInfo.InstitutionId,
    lastactivitydate = tenantUser.LastActivityDate
});


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