I´m new to ASP.NET, I want to know if someone can explain how Insert
works using a stored procedure. I'm using Dapper.
I have a product model like this:
using Dapper.Contrib.Extensions;
using System;
namespace Dto.Entities.Products
{
[Table("Product.ProductDetail")]
public class ProductDetail
{
[Key]
public int ProductDetailId { get; set; }
public int ProductId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
}
Now can someone explain me how can I do an insert in controller using a stored procedure? Regards
The quickest way is to handle all the logic in the controller as you said:
[HttpPost]
public async Task<IHttpActionResult> Post([FromBody]ProductDetail payload)
{
using (var connection = new SqlConnection("<your_connectionstring>"))
{
var parameters = new
{
ProductId = payload.ProductId,
Name = payload.Name,
Description = payload.Description
};
await connection.ExecuteAsync("<your_insert_sp>", parameters, commandType: CommandType.StoredProcedure).ConfigureAwait(false);
}
return Ok();
}
This is not the recommended way to go though.
You should always use a dto class instead of your real data model as the type going in or leaving your controller.
Also the db logic should be moved outside of the controller, for example to a repository class. Or you can use Mediatr to move your logic away from your action and keep your controllers thin.