3

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
  • 732,580
  • 175
  • 1,330
  • 1,459
Ahmed Shamel
  • 1,982
  • 3
  • 24
  • 58

6 Answers6

5

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
  • 10,077
  • 1
  • 29
  • 51
Uthman Rahimi
  • 708
  • 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
  • 42,509
  • 16
  • 113
  • 174
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,304
  • 11
  • 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,198
  • 2
  • 17
  • 27
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,417
  • 2
  • 15
  • 32
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();

}