使用 Dapper 从多个表中查询数据
Querying data from multiple tables using Dapper
我有数据库 table GTL_TITLES,它有两个外键,AuthorId
和 PublisherId
。如果我想从数据库中查询标题,我还想从 AUTHOR 和 PUBLISHER table 中获取信息。为此,我创建了一个连接所有三个 table 并选择以下列的存储过程:
我的 GtlTitle 模型 class 看起来像这样:
public string ISBN { get; set; }
public string VolumeName { get; set; }
public string TitleDescription { get; set; }
public string PublisherName { get; set; }
public DateTime PublicationDate { get; set; }
public Author TitleAuthor { get; set; }
public Publisher Publisher { get; }
如您所料,class Author 有两个字符串:FirstName
and LastName
and Publisher 有 PublisherName
.
话虽如此,这是调用数据库的方法:
public GtlTitle GetTitle(string ISBN)
{
using (var connection = new SqlConnection(_connection))
{
connection.Open();
return connection.QuerySingle<GtlTitle>("GetTitleByISBN", new { ISBN }, commandType: CommandType.StoredProcedure);
}
}
和returns以下:{"isbn":"978-0-10074-5","volumeName":"Volume Name - 97581","titleDescription":"Description - 97581","publisherName":"Publisher - 714","publicationDate":"2020-05-23T00:00:00","titleAuthor":null,"publisher":null}
如您所见,titleAuthor
和 publisher
为空。我怎样才能解决这个问题?我是否需要在 GtlTitle 模型 class 中编写 public string FirstName
之类的字段,或者是否有任何方法可以填充 Author 和 出版商
还有吗?
Dapper 通过 splitOn
参数支持多重映射,您可以通过提供新对象开始处的列名将一行拆分为多个对象。
return connection.Query<GtlTitle, Author, Publisher, GtlTitle>(sql,
(g,a,p) => {
g.TitleAuthor = a;
g.Publisher = p;
return g; },
splitOn: "FirstName,PublisherName").First();
我有数据库 table GTL_TITLES,它有两个外键,AuthorId
和 PublisherId
。如果我想从数据库中查询标题,我还想从 AUTHOR 和 PUBLISHER table 中获取信息。为此,我创建了一个连接所有三个 table 并选择以下列的存储过程:
我的 GtlTitle 模型 class 看起来像这样:
public string ISBN { get; set; }
public string VolumeName { get; set; }
public string TitleDescription { get; set; }
public string PublisherName { get; set; }
public DateTime PublicationDate { get; set; }
public Author TitleAuthor { get; set; }
public Publisher Publisher { get; }
如您所料,class Author 有两个字符串:FirstName
and LastName
and Publisher 有 PublisherName
.
话虽如此,这是调用数据库的方法:
public GtlTitle GetTitle(string ISBN)
{
using (var connection = new SqlConnection(_connection))
{
connection.Open();
return connection.QuerySingle<GtlTitle>("GetTitleByISBN", new { ISBN }, commandType: CommandType.StoredProcedure);
}
}
和returns以下:{"isbn":"978-0-10074-5","volumeName":"Volume Name - 97581","titleDescription":"Description - 97581","publisherName":"Publisher - 714","publicationDate":"2020-05-23T00:00:00","titleAuthor":null,"publisher":null}
如您所见,titleAuthor
和 publisher
为空。我怎样才能解决这个问题?我是否需要在 GtlTitle 模型 class 中编写 public string FirstName
之类的字段,或者是否有任何方法可以填充 Author 和 出版商
还有吗?
Dapper 通过 splitOn
参数支持多重映射,您可以通过提供新对象开始处的列名将一行拆分为多个对象。
return connection.Query<GtlTitle, Author, Publisher, GtlTitle>(sql,
(g,a,p) => {
g.TitleAuthor = a;
g.Publisher = p;
return g; },
splitOn: "FirstName,PublisherName").First();