0

我有一个模型“Person”,它引用了另一个模型“Salutation”。

public class Person
{
    public int Id { get; set; }
    public Boolean Active { get; set; }
    // fk
    public virtual Salutation Salutation { get; set; }
    public virtual PersonName Name { get; set; }

}

public class Salutation
{
    public int Id { get; set; }
    public string Name { get; set; }
}

当我尝试用不同的“称呼”更新“人”时,它不会更新。尽管如果我在“称呼”中更改实际数据,它确实会更新。这是我控制器中的更新代码,进入函数的数据是正确的,但只是没有保存在数据库中。

例如,如果当前称呼的 ID:1 和姓名:“先生”,那么如果我尝试传入另一个 ID:2 和姓名:“夫人”的现有记录,它不会改变。但是如果我传入 ID:2 和 Name:"RandomAlienString" 那么它确实会更改为新模型并更新称呼。

在控制器中 - 更新方法:

 public void PutPerson(int id, [FromBody]Person person)
    {
        if (!ModelState.IsValid)
        {
            throw new HttpResponseException(HttpStatusCode.BadRequest);
        }

        if (id != person.Id)
        {
            throw new HttpResponseException(HttpStatusCode.BadRequest);
        }

        db.Entry(person).State = EntityState.Modified;
        db.Entry(person.Name).State = EntityState.Modified;
        db.Entry(person.Salutation).State = EntityState.Modified;

        try
        {
            db.SaveChanges();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!PersonExists(id))
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            else
            {
                throw;
            }
        }
    }

非常感激任何的帮助。

4

0 回答 0