0

I had to update single field in my database using EF. I am doing as it like this:

1 - Load the orginal record from table based on name

2 - Update the field value

3 - save the object back to db

Code:

public void UpdateUser(List<User> users)
{
    foreach (User user in users)
    {
        Job original = _context.Users.Where(x => x.Name == user.Name).AsNoTracking().FirstOrDefault();
        if (original != null)
        {                   
            original.Name = user.Nanme;
            _context.Entry(original).State = EntityState.Modified; // not sure it is needed or not
        }
        _context.SaveChanges();           

    }
}

Is it an efficient way? Or i can do it in much better way?

simbada
  • 940
  • 4
  • 24
  • 43

2 Answers2

0

Load the original record from table based on name.

This is not really a good practices, you should get record based on id

  Job original = _context.Users.Where(x => x.id== user.id).AsNoTracking().FirstOrDefault();

And _context.SaveChanges(); should be out side of foreach, so update will perform once.

Here you need _context.Entry(original).State = EntityState.Modified;, which indicates the entity is being tracked by the context and exists in the database, and some or all of its property values have been modified.

So finally your code looks like:

foreach (User user in users)
{
  Job original = _context.Users.Where(x => x.id== user.id).AsNoTracking().FirstOrDefault();
  if (original != null)
  {                   
    original.Name = user.Nanme;
   _context.Entry(original).State = EntityState.Modified;
  }                      
}
 _context.SaveChanges(); 

Hope this helps!

Divyang Desai
  • 7,483
  • 13
  • 50
  • 76
0

How about this,

foreach (User user in users)
{
  _context.Users.Find(user.id).Name = user.Name;
}                      
_context.SaveChanges(); 
Awais Mahmood
  • 1,308
  • 4
  • 21
  • 51