How to update record using Entity Framework 7?

2019-08-12 14:15发布

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条回答
放荡不羁爱自由
2楼-- · 2019-08-12 14:49

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.

查看更多
登录 后发表回答