2

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 ?

marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425
Ahmed Shamel
  • 1,882
  • 2
  • 25
  • 54

6 Answers6

4

you can Use EntityState Like this:

var user=db.users.Find(userId);
user.name="new name";
user.age=txtAge.text;
user.address=txtAddress.text;
context.Entry(user).State=Entitystate.Modified;
Dgan
  • 9,618
  • 1
  • 28
  • 50
Uthman Rahimi
  • 698
  • 5
  • 22
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.

Cheng Chen
  • 41,149
  • 16
  • 109
  • 168
1

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.

tede24
  • 2,226
  • 10
  • 14
0

Try this,

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

                db.SaveChanges();
                return true;
            }
JanMer
  • 1,086
  • 2
  • 15
  • 24
0

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();
Seabizkit
  • 2,351
  • 2
  • 14
  • 30
0

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();

}