Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert data in child object using Dapper

Tags:

dapper

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 = "[email protected]";
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?

like image 347
Anthony Fernandes Avatar asked Feb 13 '26 05:02

Anthony Fernandes


1 Answers

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
});
like image 60
Marc Gravell Avatar answered Feb 17 '26 22:02

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!