使用Dapper查询多个表的数据。

问题描述 投票:0回答:1

我有数据库表 GTL_TITLES 其中有两个外键。AuthorIdPublisherId. 如果我想从数据库中查询一个标题,我想同时从 撰稿人出版商 表。为此,我创建了一个存储过程,将所有三个表连接起来,并选择以下列。

enter image description here

"我的 GtlTitle 模型类是这样的。

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

正如你所猜测的,类 撰稿人 有两个字符串。FirstNameLastName出版社PublisherName.

这些都是说的,这是调用数据库的方法。

public GtlTitle GetTitle(string ISBN)
    {
        using (var connection = new SqlConnection(_connection))
        {
            connection.Open();
            return connection.QuerySingle<GtlTitle>("GetTitleByISBN", new { ISBN }, commandType: CommandType.StoredProcedure);
        }
    }

并返回以下内容 {"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}

如你所见, titleAuthorpublisher 都是空的。如何解决这个问题?我是否需要写像 public string FirstNameGtlTitle 模型类来代替,或者有什么方法可以填充到 撰稿人出版社 以及?

c# sql-server api .net-core dapper
1个回答
1
投票

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

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.