首页 > 解决方案 > 如何将 JObject 作为对象添加到实体框架

问题描述

我有一个代表反序列化 jsonjobject的变量列表,我想将它们添加到实体数据库中。我怎样才能做到这一点?

到目前为止尝试的解决方案:

var obj = JsonConvert.DeserializeObject<dynamic>(strtest);

foreach (var item in obj.results)
{
    db.ReedAPIModels.Add(item);
    db.SaveChanges();
}

模型类代表数据库:

public class APIModel
{
        [Key]
        public int jobId { get; set; }
        public int employerId { get; set; }
        public string employerName { get; set; }
        public string employerProfileId { get; set; }
        public string employerProfileName { get; set; }
        public string jobTitle { get; set; }
        public string locationName { get; set; }
        public int minimumSalary { get; set; }
        public int maximumSalary { get; set; }
        public string currency { get; set; }
        public string expirationDate { get; set; }
        public string date { get; set; }
        public string jobDescription { get; set; }
        public int applications { get; set; }
        public string jobUrl { get; set; }
}

API 结果

{
  "results": [
    {
      "jobId": 39650785,
      "employerId": 375315,
      "employerName": "Spectrum IT Recruitment (South)",
      "employerProfileId": null,
      "employerProfileName": null,
      "jobTitle": "Senior Front End Developer",
      "locationName": "Reading",
      "minimumSalary": 60000,
      "maximumSalary": 70000,
      "currency": "GBP",
      "expirationDate": "17/01/2020",
      "date": "03/01/2020",
      "jobDescription": " Senior Front End Developer - Reading, Berkshire  Senior Front End Developer required by a growing company based in Reading, Berkshire. The company are looking to recruit a Senior Front End Developer to join their expanding development team to work on the full design and development lifecycle of new products. The successful Senior Front End Developer will have lots of opportunities for development of both techni... ",
      "applications": 0,
      "jobUrl": "https://www.reed.co.uk/jobs/senior-front-end-developer/39650785"
    }
  ],
  "ambiguousLocations": [],
  "totalResults": 9007
}

另外,我尝试过使用ToObject方法

标签: asp.netasp.net-mvcentity-frameworkasp.net-web-api

解决方案


您应该添加APIModel而不是ReedAPIModels.

你可以试试这种方式

var apiResult = JsonConvert.DeserializeObject<dynamic>(strtest);

foreach (var item in apiResult.results)
{
    db.APIModel.Add(item);
    db.SaveChanges();
}

推荐阅读