我正在尝试使用 dapper 的多重映射功能来返回专辑列表以及相关的艺术家和流派。
public class Artist
{
public virtual int ArtistId { get; set; }
public virtual string Name { get; set; }
}
public class Genre
{
public virtual int GenreId { get; set; }
public virtual string Name { get; set; }
public virtual string Description { get; set; }
}
public class Album
{
public virtual int AlbumId { get; set; }
public virtual int GenreId { get; set; }
public virtual int ArtistId { get; set; }
public virtual string Title { get; set; }
public virtual decimal Price { get; set; }
public virtual string AlbumArtUrl { get; set; }
public virtual Genre Genre { get; set; }
public virtual Artist Artist { get; set; }
}
var query = @"SELECT AL.Title, AL.Price, AL.AlbumArtUrl, GE.Name, GE.[Description], AR.Name FROM Album AL INNER JOIN Genre GE ON AL.GenreId = GE.GenreId INNER JOIN Artist AR ON AL.ArtistId = AL.ArtistId";
var res = connection.Query<Album, Genre, Artist, Album>(query, (album, genre, artist) => { album.Genre = genre; album.Artist = artist; return album; }, commandType: CommandType.Text, splitOn: "ArtistId, GenreId");
我已经检查了有关此的解决方案,但没有一个有效。谁能让我知道我哪里出错了?
谢谢@Alex :) 但我仍然感到震惊。这就是我所做的:
CREATE TABLE Artist
(
ArtistId INT PRIMARY KEY IDENTITY(1,1)
,Name VARCHAR(50)
)
CREATE TABLE Genre
(
GenreId INT PRIMARY KEY IDENTITY(1,1)
,Name VARCHAR(20)
,[Description] VARCHAR(1000)
)
CREATE TABLE Album
(
AlbumId INT PRIMARY KEY IDENTITY(1,1)
,GenreId INT FOREIGN KEY REFERENCES Genre(GenreId)
,ArtistId INT FOREIGN KEY REFERENCES Artist(ArtistId)
,Title VARCHAR(100)
,Price FLOAT
,AlbumArtUrl VARCHAR(300)
)
INSERT INTO Artist(Name) VALUES ('Jayant')
INSERT INTO Genre(Name,[Description]) VALUES ('Rock','Originally created during school days. The year was.....I guess 1998')
DECLARE @gen_id INT
,@art_id INT
SET @gen_id = (SELECT MAX(GenreId) FROM Genre)
SET @art_id = (SELECT MAX(ArtistId) FROM Artist)
INSERT INTO Album(GenreId,ArtistId,Title,Price,AlbumArtUrl) VALUES (@gen_id,@art_id,'I go mad for you',200,'http://asha4u.com/IGoMad')
根据您的建议,我将查询更改为:
var query = @"SELECT AL.AlbumId, AL.Title, AL.Price, AL.AlbumArtUrl, GE.GenreId, GE.Name, GE.Description, AR.ArtistId, AR.Name FROM Album AL INNER JOIN Artist AR ON AR.ArtistId = AL.ArtistId INNER JOIN Genre GE ON GE.GenreId = AL.GenreId";
var res = connection.Query<Album, Genre, Artist, Album>(query, (album, genre, artist) => { album.Genre = genre; album.Artist = artist; return album; }, commandType: CommandType.Text, splitOn: "GenreId, ArtistId");
现在我对 GenreId 和 ArtistId 使用 splitOn。我仍然得到同样的错误。请帮忙。