使用Dapper在子对象中插入数据

时间:2014-07-09 22:36:57

标签: dapper

我有以下课程

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; }
}

我能够成功使用Dapper检索信息:

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");

如何将数据插入TenantUser表?

我试过了:

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);

由于InstitutionId是子对象TenantInfo中的属性,我得到了 错误:&#34;必须声明标量变量\&#34; @institutionid \&#34;。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

Dapper故意过于简单化。在您的方案中,您必须展平数据 - 至少对于insert

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