我正在尝试使用Dapper执行以下操作(并且失败)。
我的POCO(简化所有代码)是:
public class Company
{
public int CompanyId { get; private set; }
public string CompanyName { get; private set; }
public Person CompanyAddress { get; private set; }
public Person Administrator { get; private set; }
}
public class Person
{
public int PersonId { get; private set; }
public string FirstName { get; private set; }
public string LastName { get; private set; }
}
在数据库中,Company表有一个FK for CompanyAddress和Administrator,它映射到Person表中的PersonID PK。根据{{3}}和this我认为以下是我想要这样做的方式:
public static Company Select(IDbConnection connection, int id)
{
Trap.trap();
return connection.Query<Company, Person, Person, Company>("select * from Company left join Person address on Company.CompanyAddress = address.PersonId left join Person admin on Company.Administrator = admin.PersonId where Company.CompanyId = @Id",
(cmpy, addr, admin) => new { PersonId = id }).FirstOrDefault();
}
但是这给了我一个关于“new {PersonId = id}”的编译错误。我错了什么?
答案 0 :(得分:1)
您需要提供SplitOn
参数来指定下一个表/类的起始位置。您也不应该创建匿名类型,而是使用新范围来初始化Administrator
的{{1}}属性:
Company
但是,由于你有两个连接到同一个表,我不确定它是否已经有效。所以我认为你需要所有重复列的别名,如string sql = @"select c.CompanyId,c.CompanyName, c.CompanyAddress,
address.PersonId, etc. ....
from Company c
left join Person address
on Company.CompanyAddress = address.PersonId
left join Person admin
on Company.Administrator = admin.PersonId
where Company.CompanyId = @Id";
string splitOn = "PersonId"; // maybe two parameters separated by comma, see comment below the answer
return connection.Query<Company, Person, Person, Company>(sql,
(Company cmpy, Person addr, Person admin) => { cmpy.Administrator = admin; return cmpy; }
,null,null,true,splitOn)
.FirstOrDefault();
。但无论如何,这个迁移都会有所帮助。