2

If I have code that updates an entry, and the update only changes two columns with the rest remaining the same after inputting data for maybe ten columns, does it save all ten columns or only the two that change?

If I update 10 columns but nothing changes in each one, does it bother doing the update?

Example

col1 | col2 | col3
-----|------|-----
1    |2     |3

Update col1 to 1, col2 to 2, and col3 to 4. Does is save all three or only col3 since it was the only one that changed?

If I update col1 to 1, col2 to 2, and col3 to 3, nothing changed so does it update still?

On that note, how can I see the SQL generated by SaveChanges?

Kayot
  • 582
  • 2
  • 20
  • See [this answer](http://stackoverflow.com/questions/1412863/how-do-i-view-the-sql-generated-by-the-entity-framework/20751723#20751723) on how to view the SQL generated by EF – Maria Ines Parnisari Dec 28 '16 at 14:30
  • It depends on how you're using EF. If the entity you're modifying is attached, it will only update the changed columns. If it's not attached and you don't retrieve the current values before saving, it will update all columns but the primary key. – jrummell Dec 28 '16 at 14:34

2 Answers2

0

You can see the generated code SQL by EF using the SQL PROFILER (in the tools of SQL Server or other for Mysql)

federico scamuzzi
  • 3,708
  • 1
  • 17
  • 24
0

Some one posted an answer but removed it before I could add a comment. So here is their answer plus my own.

Yes, in short it only updates the columns that change. This assumes that you are using context (not fully sure what that means)

To test this I used a log in Trace.

Using DB As New wotcDB
    DB.Database.Log = Sub(val) Diagnostics.Trace.WriteLine(val)

    Dim Update = (From t In DB.interview_income
                  Where t.ID = IncomeID).First
    Update.Company = If(String.IsNullOrEmpty(txtCompany.Text), Nothing, txtCompany.Text)
    Update.StartDate = If(IsNothing(txtStartDate.DateValue), Nothing, txtStartDate.DateValue)
    Update.EndDate = If(IsNothing(txtEndDate.DateValue), Nothing, txtEndDate.DateValue)
    Update.HWM = If(String.IsNullOrEmpty(cboHWT.Text), Nothing, cboHWT.Text)
    Update.Wage = txtWage.DecimalValue
    Update.Units = If(String.IsNullOrEmpty(txtHourPerWeek.Text), Nothing, CDec(txtHourPerWeek.Text))
    Update.Adj = txtAdj.DecimalValue
    Update.Total = txtTotal.DecimalValue
    DB.SaveChanges()
End Using

The line

DB.Database.Log = Sub(val) Diagnostics.Trace.WriteLine(val)

Writes all generated SQL to the trace. When I did a update where none of the values changed, it didn't bother generating an update statement. When I changed one column it generated an update that only had that column and key.

So, two answers in one. Use that Database log to see your generated SQL, and yes it only updates when it needs to.

Kayot
  • 582
  • 2
  • 20