Creating a repository method to add an answer

The last method we are going to implement is for adding an answer to a question:

public AnswerGetResponse PostAnswer(AnswerPostRequest answer)
{
using (var connection = new SqlConnection(_connectionString))
{
connection.Open();
return connection.QueryFirst<AnswerGetResponse>(
@"EXEC dbo.Answer_Post
@QuestionId = @QuestionId, @Content = @Content,
@UserId = @UserId, @UserName = @UserName,
@Created = @Created",
answer
);
}
}

As well as inserting the answer into the database table, the stored procedure returns the saved answer. So, we use the Dapper QueryFirst method to execute the stored procedure and return the saved answer.

We also need to create the AnswerPostRequest model class in the models folder:

public class AnswerPostRequest
{
public int QuestionId { get; set; }
public string Content { get; set; }
public string UserId { get; set; }
public string UserName { get; set; }
public DateTime Created { get; set; }
}

That completes our data repository. We've chosen to have a single method containing all of the methods to read and write data. We can, of course, create multiple repositories for different areas of the database, which would be a good idea if the app was larger.

As we add features to our app that involve database changes we'll need a mechanism of deploying the database changes. We'll look at this in the next section.

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

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