使用Entity Framework将{api端点请求保存到DB

时间:2016-07-05 17:17:49

标签: c# json serialization

我一直在进行大量搜索,但尚未找到有关此问题的任何相关信息。我想知道是否有人能指出我如何能够实现以下目标:

所以我试图做的是做一个api端点请求并将结果保存到我的数据库中。

这是我的控制人员:

public class Reference_ManufacturersController : ApiController
{
    private DataEntities db = new DataEntities();
    static string _address = "http://localhost:57454/api/Reference_Manufacturers?format=json";
    private Reference_Manufacturers result;

    // GET: api/Reference_Manufacturers
    public async Task<IEnumerable<Reference_Manufacturers>> GetReference_Manufacturers()
    {
        Reference_Manufacturers resultset = await GetResponse();
        db.Reference_Manufacturers.Add(resultset);
        await db.SaveChangesAsync();
        return db.Reference_Manufacturers;
    }

    private async Task<Reference_Manufacturers> GetResponse()
    {
        var client = new HttpClient();
        HttpResponseMessage response = await client.GetAsync(_address);
        response.EnsureSuccessStatusCode();
        result = await response.Content.ReadAsAsync<Reference_Manufacturers>();
        return result;
    }
}

运行此操作时会发生以下异常:

  

ExceptionMessage

     

无法将当前JSON数组(例如[1,2,3])反序列化为类型&#39; DIA_FirearmsAPIversion2.Models.Reference_Manufacturers&#39;因为类型需要JSON对象(例如{&#34; name&#34;:&#34; value&#34;})才能正确反序列化。要修复此错误,请将JSON更改为JSON对象(例如{&#34; name&#34;:&#34; value&#34;})或将反序列化类型更改为实现集合接口的数组或类型(例如ICollection,IList)就像可以从JSON数组反序列化的List。 JsonArrayAttribute也可以添加到类型中以强制它从JSON数组反序列化。路径&#39;&#39;,第1行,第1位。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

我弄清楚我在忽视和做错了什么。 我没有使用各种容器来保存所有返回的值。

public class Reference_ManufacturersController : ApiController
{
    private DataEntities db = new DataEntities();
    static string _address = "http://localhost:57454/api/Reference_Manufacturers?format=json";
    private List<Reference_Manufacturers> result;

    // GET: api/Reference_Manufacturers
    public async Task<IEnumerable<Reference_Manufacturers>> GetReference_Manufacturers()
    {
        List<Reference_Manufacturers> resultset = await GetResponse();
        foreach (Reference_Manufacturers manu in resultset)
        {
            db.Reference_Manufacturers.Add(manu);
        }
        await db.SaveChangesAsync();
        return db.Reference_Manufacturers;
    }

    private async Task<List<Reference_Manufacturers>> GetResponse()
    {
        var client = new HttpClient();
        HttpResponseMessage response = await client.GetAsync(_address);
        response.EnsureSuccessStatusCode();
        result = await response.Content.ReadAsAsync<List<Reference_Manufacturers>>();
        return result;
    }}