simbada
simbada

Reputation: 980

how do i check if property actually change before an update

I am using EF 5 (not 6). I have an object of below class and it is in DB using EF.

public class Student
{
  public string Name { get; set; }
  public int Age { get; set; }
  public DateTime DOB { get; set;}
}

Later on,

I got request to make an update to same object / record.

But before making update call , i would like to cross compare whether property actually changed because i may get the same record for an update so don't want to make blind update.

 var student = _context.Students.select(x =>x.Name == "").first();
 student.name = "";
 student.age = "";
 student.DOB = "";
_context.Entry(student).State = EntityState.Modified;
_context.saveChanges();

Does EF gives me some built in way to this?

Or, I need to cross compare each property one by one and decide? I can have 20 properties ...

Any idea please?

Upvotes: 5

Views: 14048

Answers (3)

Anonymous Duck
Anonymous Duck

Reputation: 2998

Starting with EF 6

context.ChangeTracker.HasChanges()

Please refer to the documentation

Checks if the DbContext is tracking any new, deleted, or changed entities or relationships that will be sent to the database if SaveChanges is called.

DBChangeTracker Class

Or you can read from this blog how this method Secrets of DetectChanges

UPDATE: For EF 5, there is an alternative

return this.ChangeTracker.Entries().Any(e => e.State == EntityState.Added
                                              || e.State == EntityState.Modified
                                              || e.State == EntityState.Deleted);

This answer is not mine, I take it from this answer so give credit to the right person.

Upvotes: 7

Barr J
Barr J

Reputation: 10927

The statement below:

_context.Entry(student).State = EntityState.Modified;
_context.saveChanges();

Will update all the relevant field of the entity, thus marked as dirty.

On the code behind it is like this:

UPDATE student
SET Value 1 = 'whatever student name is',
    Value 2 = 'whatever student name is'
WHERE Id = 123; 

If you want to update specific value, please use the

_context.Student.Attach(student)

Which on the code behind will look like this:

    UPDATE student
    SET Value 1 = 'whatever student name is'
WHERE Id = 123;

If you want to check if property changed before the update override the equals method of your object and compare the properties you desire:

public override bool Equals(object obj)
{
    return MyProperty == ((MyObject)obj).MyProperty
}

Upvotes: 2

Perdido
Perdido

Reputation: 238

The Equals method and the IEquatable<T> interface could be used to know if two objects are equal but they won't allow you to know the differences between the objects.

Upvotes: 0

Related Questions