使用存储过程插入项目

Insert an item using stored procedure

我是 ASP.NET 的新手,我想知道是否有人可以解释 Insert 如何使用存储过程。我正在使用 Dapper。

我有这样的产品型号:

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; }
    }
}

现在有人可以解释一下如何使用存储过程在控制器中插入吗?问候

最快的方法是像你说的那样处理控制器中的所有逻辑:

[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();
}

不过,这不是推荐的方法。

您应该始终使用 dto class 而不是您的真实数据模型作为进入或离开控制器的类型。

数据库逻辑也应移出控制器,例如移至存储库 class。或者你可以使用 Mediatr to move your logic away from your action and keep your controllers thin.