Entity Framework - not updating referenced model

痴心易碎 提交于 2019-12-24 23:09:56

问题


I have a model, 'Person', that references another model, '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; }
}

when I try and UPDATE the 'Person' with a different 'Salutation' it doesn't update. Though if I change the actual data within the 'salutation' it does update. This is the UPDATE code in my controller, the data coming in to the function is correct but just doesn't save in the DB.

For example if the current Salutation has ID: 1 and Name: "Mr" then if I try and pass in a different existing record with ID: 2 and Name: "Mrs" it doesn't change. But if I pass in ID:2 and Name:"RandomAlienString" then it DOES change to the new model and updates the Salutation.

In the controller - UPDATE Method:

 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;
            }
        }
    }

Any help would be most appreciated.

来源:https://stackoverflow.com/questions/22466419/entity-framework-not-updating-referenced-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!