'Update multiple columns in Entity Framework

I want to update multiple columns in Entity Framework. I now use this :

var user = new Relations { Id=1, Status = 1, Date = DateTime.Now, Notification = 0 };

db.Relations.Attach(user);

db.Entry(user).Property(x => x.Status).IsModified = true;
db.Entry(user).Property(x => x.Notification).IsModified = true;
db.Entry(user).Property(x => x.Date).IsModified = true;

db.Configuration.ValidateOnSaveEnabled = false;
db.SaveChanges();

Is there a better way to update columns without repeating the code db.Entry(user).Property several times ?



Solution 1:[1]

I prefer use:

var existingUser = context.Set<User>().Where(u => u.Id == 1);
context.Entry(existingUser).CurrentValues.SetValues(user);

Or you can use a 3rd lib like GraphDiff.

Solution 2:[2]

Yo update an entity you don't need to do this:

// build your entity object with new values
var user = new Relations { Id=1, Status = 1, Date = DateTime.Now, Notification = 0 };
//attach as modified in one single step
db.Entry(user).State = EntityState.Modified;
//execute update
db.SaveChanges();

This assumes you are setting all entity fields and there isn't RowVersion field in your entity. Extra steps would be required to manage these other situations.

Solution 3:[3]

Try this,

using (var db = new YourDb())
            {
                try
                {
                    db.Entry(user).State = EntityState.Modified;
                }
                catch (Exception)
                {
                    return false;
                }

                db.SaveChanges();
                return true;
            }

Solution 4:[4]

When an item is fetched via the context it is

automatically tracked in that context unless you change the default behavior.

So you could simple do:

var txtInputAge = 18;
var txtAdrressLine1 = "Some cool place"

//fetch the user
var user = db.Users.Find(userId);

//change the properties
user.Name = "new cooler name";
user.Age = txtInputAge;
user.Address = txtAdrressLine1;

//call save changes
db.SaveChanges();

Update - Add would look like

//create new entry
User user = new User();

user.Name = "new cooler name";
user.Age = txtInputAge;
user.Address = txtAdrressLine1;

//add to context
db.Users.Add(user);

//call save changes
db.SaveChanges();

Solution 5:[5]

using (var dbcontext = new MyModel()) {

var matchedRecords = dbcontext.DummyTable.Where(e => e.code.Equals(entry.code) &&
e.isValid.Equals(true)).ToList();
matchedRecords.ForEach(e => e.isValid = false);
dbcontext.SaveChanges();

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Cheng Chen
Solution 2 tede24
Solution 3 JanMer
Solution 4
Solution 5 sagar jadhav