我有一个SQLite表"短语"像:
CREATE TABLE [phrases] (
[id] INTEGER PRIMARY KEY AUTOINCREMENT,
[phrase] CHAR,
[parent_id] INTEGER);
我用演示数据填充它:
id | phrase | parent_id
1 | parent phrase | (null)
2 | some child 1 | 1
3 | some child 2 | 1
我有一个C#模型,如:
class Phrase
{
int id { get; set; }
string phrase { get; set; }
int parent_id { get; set; }
Phrase parent { get; set; }
}
如何正确使用Dapper将此表映射到此类? 感谢。
答案 0 :(得分:0)
您需要在选择查询中添加短语child(我使用MS-SQL):
SELECT p.id AS id,
p.phrase AS phrase,
p.parent_id AS parent_id,
c.id AS id,
c.phrase AS phrase
FROM phrases p
LEFT JOIN phrases c ON p.id = c.parent_id
Dapper能够通过假设您的Id列被命名为Id或id(默认情况下)来拆分返回的行。
C#:
public IEnumerable<Phrase> GetPhrase()
{
const string sql = @" SELECT p.id AS id,
p.phrase AS phrase,
p.parent_id AS parent_id,
c.id AS id,
c.phrase AS phrase
FROM phrases p
LEFT JOIN phrases c ON p.id = c.parent_id";
using (var connection = OpenConnection(_connectionString))
{
return connection.Query<Phrase, Phrase, Phrase>(sql, (p, c) =>
{
p.parent = c;
return p;
}, commandType: CommandType.Text);
}
}