将对象列表插入数据库?

时间:2019-09-27 08:11:32

标签: c# sql-server http

我一直在努力为数据库中某些表的CRUD创建API。我做了一次只能添加一种成分的功能,现在我想弄清楚如何制作一种可以一次添加多种成分的方法。

下面是配料的模型类别。 ( RecipeIngredient.cs

public class RecipeIngredient
{
    public int id { get; set; }
    public int recipeId { get; set; }
    public string displayName { get; set; }
    public float amount { get; set; }
    public int recipeIngredientUnitId { get; set; }
    public int productId { get; set; }
    public int displayOrder { get; set; }
    public string ingredientGroup { get; set; }
    public int virtualProductId { get; set; }


    public RecipeIngredient(int id, int recipeId, string displayName, float amount, int recipeIngredientUnitId, int productId, int displayOrder, string ingredientGroup, int virtualProductId)
    {
        this.id = id;
        this.recipeId = recipeId;
        this.displayName = displayName;
        this.amount = amount;
        this.recipeIngredientUnitId = recipeIngredientUnitId;
        this.productId = productId;
        this.displayOrder = displayOrder;
        this.ingredientGroup = ingredientGroup;
        this.virtualProductId = virtualProductId;

    }

这是 RecipeIngredientController.cs

 [Route("v1/recipeIngredient")]
 [HttpPost()]
 public IActionResult AddIngredient([FromBody]RecipeIngredient ingredient)
 {
      var productId = 1;
      var displayOrder = 1;
      var virtualProductId = 1;
      var ingredientGroup = "TBA";
      try
      {
          if (ingredient == null) throw new ArgumentException("No data specified");

          using (var con = _connFactory())
          {
              con.Open();
              con.Execute("INSERT INTO dbo.RecipeIngredient (Id, RecipeId, DisplayName, Amount, RecipeIngredientUnitId, ProductId, DisplayOrder, IngredientGroup, VirtualProductId) " +
                            "VALUES ((SELECT MAX(ID) + 1 FROM dbo.RecipeIngredient), @recipeId, @displayName, @amount, @recipeIngredientUnitId, @productId, @displayOrder, @ingredientGroup, @virtualProductId)",
                          new
                          {
                              //ingredient.id,
                              ingredient.recipeId,
                              ingredient.displayName,
                              ingredient.amount,
                              ingredient.recipeIngredientUnitId,
                              productId,
                              displayOrder,
                              ingredientGroup,
                              virtualProductId
                          });
          }
          return Ok(ingredient);
      }
      catch (Exception exc)
      {
          return BadRequest();
      }
  }

如何更改模型类/(重新)编写POST方法,以便能够一次在数据库中添加多个RecipeIngredient对象?

0 个答案:

没有答案