Creating a repository method to add a new question

Let's create the PostQuestion method in DataRepository.cs to add a new question:

public QuestionGetSingleResponse PostQuestion(QuestionPostRequest question)
{
using (var connection = new SqlConnection(_connectionString))
{
connection.Open();

var questionId = connection.QueryFirst<int>(
@"EXEC dbo.Question_Post
@Title = @Title, @Content = @Content,
@UserId = @UserId, @UserName = @UserName,
@Created = @Created",
question
);

return GetQuestion(questionId);
}
}

This is a very similar implementation to the methods that read data. We use the QueryFirst Dapper method because the stored procedure returns the ID of the new question after inserting it into the database table. Our method returns the saved question by calling the GetQuestion method with questionId that was returned from the Question_Post stored procedure.

We've used a model class called QuestionPostRequest for Dapper to map to the SQL parameters. Let's create this class in the models folder:

public class QuestionPostRequest
{
public string Title { get; set; }
public string Content { get; set; }
public string UserId { get; set; }
public string UserName { get; set; }
public DateTime Created { get; set; }
}

Great stuff! That's our first write method created.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.90.25