简体   繁体   中英

How can I use Dapper with a SELECT stored procedure containing an INNER JOIN between two tables?

I am experimenting with Dapper for the first time. I have two tables: Films and Ratings.

CREATE TABLE [dbo].[Films]
(
    [Id] INT NOT NULL PRIMARY KEY, 
    [Title] VARCHAR(250) NOT NULL, 
    [Genre] VARCHAR(50) NOT NULL, 
    [RatingId] INT NOT NULL, 
    CONSTRAINT [FK_Films_To_Ratings] FOREIGN KEY (RatingId) REFERENCES Ratings(Id)
)

CREATE TABLE [dbo].[Ratings]
(
    [Id] INT NOT NULL PRIMARY KEY, 
    [Name] VARCHAR(50) NOT NULL 
)

I have written a stored procedure that will return all films in the Films table and joins with the Ratings table. Dapper works easily when I have the table structured using the same name between the FK and PK of the tables.

CREATE PROCEDURE [dbo].[GetFilms]
AS
BEGIN
    SELECT
        F.Id,
        F.Title,
        F.Genre,
        F.RatingId,
        R.Name
    FROM
        dbo.Films as F
    INNER JOIN
        dbo.Ratings as R
    ON
        F.RatingId = R.Id;
END

When my query runs, the film object becomes instantiated correctly but the RatingId was set to 0 (since int defaults to 0). The rating property contains the name, but the Id was also set to 0.

return this._db.Query<Film, Rating, Film>(
            "dbo.GetFilms",
            (f, r) =>
            {
                f.Rating = r;
                return f;
            },
            splitOn: "RatingId",
            commandType: CommandType.StoredProcedure
            ).ToList();

How can I successfully run my Dapper query and get the exact results I need when the column names are not identical like in my example? Table structure looks cleaner to me when I have columns named Ratings.Id instead of Ratings.RatingId.

Dapper will try and map property for property at the point you start splitting. You want your query to look like the following, and you can ditch the splitOn since you are splitting on Id.:

    SELECT
            F.Id,
            F.Title,
            F.Genre,
--Rating object starts here
            R.Id,
            R.Name
        FROM
            dbo.Films as F
        INNER JOIN
            dbo.Ratings as R
        ON
            F.RatingId = R.Id;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM