How to update record using Entity Framework 7?

岁酱吖の 提交于 2019-12-24 16:15:08

问题


I am trying to update a field with various related tables using the EntityState.Modified but SaveChanges() is not applying the changes. I am using postman to post to the localhost/8000/api/co/1 and the status says 202 accepted. My repository is returning the record but it is not modified at all.

Question What am I missing in my repository for the changes to take in affect? Do I need to set each property individually? (I have hundreds)

Most the examples I can find related to the repository pattern and the entity framework 7, only utilize the EntityState.Modified(), then save changes. Can someone please help me point out what I am missing? I have my other repositories working fine that create, delete and get working just fine

My Repository

public COMP Update(int id)
{
    var original = _context.Complaints.Where(c => c.COMP_ID == id).FirstOrDefault<COMPLAINT>();
    _context.Entry(original).State = EntityState.Modified;
    SaveAll();
    return original;
}

public bool SaveAll()
{
    return _context.SaveChanges() > 0;
}

回答1:


I don't see where you are actually make any changes to entity at all. You should be pulling the original entity, make your changes and then call SaveChanges() to commit them :

public COMP Update(int id, string name)
{
    // Grab your entity
    var original = _context.Complaints.FirstOrDefault(c => c.COMP_ID == id);
    // Make your changes here (using a parameter)
    original.Name = name;
    // Save your changes
    SaveAll();
    // Return your original entity with the changes made
    return original;
}

In the above scenario, let's say you used Postman to update this particular entity and passed in the id and name as parameters (for example purpose, we will assume that this method just updates the name).

If you do that, then you could use the name parameter to update your existing entity as such :

// Make your changes here (using a parameter)
original.Name = name;

Then calling the SaveChanges() method will actually perform the update in your database.

If you have Change Tracking enabled on your context, you shouldn't need to worry about manually setting the modified states either.



来源:https://stackoverflow.com/questions/36457128/how-to-update-record-using-entity-framework-7

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