EntityFramework Web API更新了许多关系

时间:2017-10-31 12:37:14

标签: c# entity-framework

我是Entity Framework的新手,我有以下几种情况:

我有两个实体: - 解决方案 - 类别

一个类别可以有很多解决方案,一个解决方案可以有很多类别。我通过REST收到一个更新的解决方案,其中包含现在属于解决方案的类别列表,但我似乎无法更新关系:

public async Task<IHttpActionResult> PutSolution(int id, Solution solution)
    {
        if (!ModelState.IsValid)
            return BadRequest(ModelState);

        if (id != solution.ID)
            return BadRequest();

        if (!SolutionExists(id))
            return NotFound();

        db.Entry(solution).State = EntityState.Modified;


        try
        {
            await db.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            throw;
        }

        return StatusCode(HttpStatusCode.NoContent);
    }

代码在db.Entry(解决方案).State = EntityState.Modified上打破了消息:

  

附加“ForgeITAPI.Models.Solution”类型的实体失败   因为同一类型的另一个实体已经具有相同的主要实体   核心价值。使用“附加”方法或设置时可能会发生这种情况   如果有任何实体,则实体的状态为“未更改”或“已修改”   图表具有冲突的键值。这可能是因为一些   实体是新的,尚未收到数据库生成的密钥   值。在这种情况下,使用“添加”方法或“已添加”实体状态   跟踪图形,然后将非新实体的状态设置为   “视情况而定”或“修改”。

编辑:REST对象:

{
   "id":7,
   "title":"New Solution",
   "resume":"teste",
   "fullDescription":"<p>teste sdgrasdfgfdashfdsh<br></p>",
   "categories":[
      {
         "id":1,
         "name":"Augmented Reality",
         "solutions":[
            {
               "id":1,
               "title":"teste",
               "resume":"This project is awesome. 1",
               "fullDescription":"<p>Teste<br></p>",
               "categories":[

               ],
               "multimedia":null,
               "bulletPoints":null,
               "creationDate":"1900-01-01T00:00:00",
               "state":0
            }
         ],
         "newsPosts":[

         ],
         "$$hashKey":"object:16"
      },
      {
         "id":4,
         "name":"Virtual Reality",
         "solutions":[
            {
               "id":1,
               "title":"teste",
               "resume":"This project is awesome. 1",
               "fullDescription":"<p>Teste<br></p>",
               "categories":[
                  {
                     "id":1,
                     "name":"Augmented Reality",
                     "solutions":[

                     ],
                     "newsPosts":[

                     ]
                  }
               ],
               "multimedia":null,
               "bulletPoints":null,
               "creationDate":"1900-01-01T00:00:00",
               "state":0
            }
         ],
         "newsPosts":[

         ],
         "$$hashKey":"object:17"
      }
   ],
   "multimedia":[

   ],
   "bulletPoints":null,
   "creationDate":"1900-01-01T00:00:00",
   "state":0,
   "status":"Draft",
   "creationDateString":"1 of January 1900",
   "$$hashKey":"object:9"
}

0 个答案:

没有答案