Json 多数组的 C# Web API POST 方法

标签 c# arrays json entity-framework asp.net-web-api2

我正在做一个项目,该项目需要一个多数组 Json 的 POST 方法,其中数据位于 5 个不同的相关表上,具有 FK。

这是使用 GET 的 Json 输出:

{
  "UserId": 1,
  "Id": 1,
  "ValueStoryName": "Value Story 101",
  "Organization": "Charity Foundation",
  "Industry": "Education",
  "Location": "Singapore",
  "AnnualRevenue": 1000,
  "CreatedDate": "2017-07-27T00:00:00",
  "ModifiedDate": "2017-01-01T00:00:00",
  "BusinessValueToYou": [
    {
      "Id": 1,
      "BVUSId": 1,
      "BalanceSheet": 348,
      "IncomeStatement": 546,
      "ValueDriver": [
        {
          "BVUSId": 1,
          "BVUId": 1,
          "ValueDriver": "Give kind to others",
          "Selected": true,
          "TotalSavings": 0,
          "SubLever": [
            {
              "BVUId": 1,
              "BVUSVDId": 1,
              "Item": "Help when needed",
              "Selected": true,
              "EstAnnualValue": 1,
              "UserInput": [
                {
                  "BVUSVDId": 1,
                  "BVUUIId": 1,
                  "Item": "Total Benefit",
                  "UserInput": 10
                }
              ]
            }
          ]
        }
      ]
    }
  ]
}

我目前在 Controller 下的 POST 方法是:

// POST: api/ValueStories
[ResponseType(typeof(ValueStory))]
public async Task<IHttpActionResult> PostValueStory(ValueStory valueStory)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    db.ValueStories.Add(valueStory);
    db.BusinessValueToYou.AddRange(valueStory.BusinessValueToYou);

    await db.SaveChangesAsync();

    return CreatedAtRoute("DefaultApi", new { id = valueStory.Id }, valueStory);
}

上面的代码只为valuestory 和businessvaluetoyou 添加数据,而不能为valuedriver、subvaluedriver 和userinput 添加数据。我一直在绞尽脑汁思考如何使这项工作发挥作用,但没有成功。非常感谢任何帮助和引用。

这是我的 BusinessValueToYou 模型:

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace AribaWebService.Models
{
    public class BusinessValueToYou
    {
        // Foreign Key
        public int Id { get; set; }
        [Key]
        public int BVUSId { get; set; }
        public decimal BalanceSheet { get; set; }
        public decimal IncomeStatement { get; set; }

        // Navigation property
        public virtual ValueStory ValueStory { get; set; }

        public List<BVUValueDriver> ValueDriver { get; set; }

    }
    public class BVUValueDriver
    {
        // Foreign Key
        public int BVUSId { get; set; }
        [Key]
        public int BVUId { get; set; }
        [Required]
        public string ValueDriver { get; set; }
        public bool Selected { get; set; }
        public decimal TotalSavings { get;  set;}

        // Navigation property
        public virtual BusinessValueToYou BusinessValueToYou { get; set; } 

        public List<BVUSubValueDriver> SubLever { get; set; }
        }

    public class BVUSubValueDriver
    {
        // Foreign Key
        public int BVUId { get; set; }
        [Key]
        public int BVUSVDId { get; set; }
        [Required]
        public string Item { get; set; }
        public bool Selected { get; set; }
        public decimal EstAnnualValue { get; set; }


        // Navigation property
        public virtual BVUValueDriver BVUValueDriver { get; set; }

        public List<BVUUserInput> UserInput { get; set; }

    }

    public class BVUUserInput
    {
        // Foreign Key
        public int BVUSVDId { get; set; }
        [Key]
        public int BVUUIId { get; set; }
        [Required]
        public string Item { get; set; }
        public double UserInput { get; set; }

        // Navigation property
        public virtual BVUSubValueDriver BVUSubValueDriver { get; set; }

    }
}

这是我的 ValueStory 模型:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace AribaWebService.Models
{
    public class ValueStoryDetailDTO
    {
        // Foreign Key
        public int UserId { get; set; } 
        [Key]
        public int Id { get; set; }
        public string ValueStoryName { get; set; }
        public string Organization { get; set; }
        public string Industry { get; set; }
        public string Location { get; set; }
        public string Currency { get; set; }

        public double AnnualRevenue { get; set; }
        public DateTime CreatedDate { get; set; }
        public DateTime ModifiedDate { get; set; }

        // Navigation property
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public virtual User User { get; set; }

        public List<AreaOfInterest> AreaOfInterest { get; set; }
        public List<BusinessValueToYou> BusinessValueToYou { get; set; }
        public List<BusinessValueFromSap> BusinessValueFromSap { get; set; }


    }
}

最佳答案

通常我们不会直接在 web api 中公开真实的 Db 实体,只是使用 View 模型或 DTO 返回我们需要的内容以防止过度公开。

您可以更改 get 方法以在单个模型中返回您需要的内容。

了解有关自动映射器的更多信息 http://automapper.org/

构建更好的 RESTful api:https://www.codeproject.com/Articles/990492/RESTful-Day-sharp-Enterprise-Level-Application

对于您的问题,这是一个如何读取多个数组的示例:

// POST: api/ValueStories
public async Task<IHttpActionResult> PostValueStory(AbcViewModel viewModel)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    //Manual map or use Automapper here
    var entity = Mapper.Map<ValueStory>(viewModel);
    db.ValueStories.Add(entity);
    //db.BusinessValueToYou.AddRange(entity.BusinessValueToYou); // can map with automapper

    await db.SaveChangesAsync();

    return CreatedAtRoute("DefaultApi", new { id = entity .Id }, entity );
}

public class AbcViewModel
{
    public int UserId { get; set; }
    public int Id { get; set; }
    public string ValueStoryName { get; set; }
    public string Organization { get; set; }
    public string Industry { get; set; }
    public string Location { get; set; }
    public string AnnualRevenue { get; set; }
    public DateTime CreatedDate { get; set; }
    public DateTime ModifiedDate { get; set; }
    public IEnumerable<BusinessValueToYouViewModel> BusinessValueToYou { get; set; }

}

public class BusinessValueToYouViewModel
{
    public int Id { get; set; }
    public int BVUSId { get; set; }
    public int BalanceSheet { get; set; }
    public int IncomeStatement { get; set; }
    public IEnumerable<ValueDriverViewModel> ValueDriver { get; set; }
}

public class ValueDriverViewModel
{
    public int Id { get; set; }
    public int BVUSId { get; set; }
    public int BVUId { get; set; }
    public string ValueDriver { get; set; }
    public bool Selected { get; set; }
    public int TotalSavings { get; set; }
}

关于Json 多数组的 C# Web API POST 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45603893/

相关文章:

c# - Excel-DNA——模板化的 CustomTaskPane 异常

c# - 一个有恒星、银河系和其他东西的星系 (WPF)

c# - 如何将 int[] 转换为 short[]?

arrays - 获取Scheme中向量的第一个元素

ajax - 在 Django 中使用 fileReader.readAsDataURL 通过 Ajax 传输图像并在 PIL 中打开

c# - 在 <p> 标记内渲染时删除冗余空格

c - alloca 是完全可替换的吗?

json - NodeJS-ExpressJS mongoose API POST 请求带外键

python - 如何处理JSON格式的字符串?

c# 使用 WebClient 下载文件并保存