Search⌘ K
AI Features

Creating a Repository Method to Get a Single Question

Explore how to implement repository methods with Dapper to retrieve a single question and its related answers from the database. Learn to handle null results, organize response models, and use stored procedures for efficient data querying in ASP.NET Core projects.

Let’s implement the GetQuestion method now:

  1. Start by opening the connection and executing the Question_GetSingle stored procedure:

Node.js
public QuestionGetSingleResponse GetQuestion(int
questionId)
{
using (var connection = new
SqlConnection(_connectionString))
{
connection.Open();
var question =
connection.QueryFirstOrDefault<
QuestionGetSingleResponse>(
@"EXEC dbo.Question_GetSingle @QuestionId =
@QuestionId",
new { QuestionId = questionId }
);
// TODO - Get the answers for the question
return question;
}
}

This method is a little different from the previous methods because we are using the QueryFirstOrDefault Dapper method to return a single record (or null if the record isn’t found) rather than a collection of records.

    ...