Search code examples
c#linqlinq-to-sqlsubmitchanges

Updating with Linq-2-Sql: Editing private fields doens't trigger update, editing public properties does. Why?


I'm creating an edit-page for a user's profile in C# with MVC. As goes with these sort of pages, I get the information out of my database and display it in a form, and let the user change the fields to his/her liking.

After the validation, I obviously want to submit the data back into the database and this is where something occurred that I just couldn't figure out.

If I assign the new values via the private fields nothing gets submitted to the database, if I use the Property accessors the values do get submitted.

public partial class User {
    public static bool Edit(User update) {
        try {
            using (var db = new DataClassesBabysitterDataContext()) {
                User old = db.Users.Single(u => u.Id == update.Id);

                // This works
                // -------------------------------------
                old.Description = update.Description;

                // This does not
                // -------------------------------------
                old._Description = update._Description

                db.SubmitChanges();
            }

            return true;
        }
        catch (Exception e) {
            DBLogger.LogException(e);
            return false;
        }
    }
}

I honestly have no idea why this would make a difference?


Solution

  • Linq2SQL uses INotifyPropertyChanged and events in property setters to know that an instance has changed. Setting the property with a new value triggers the the event and so allows tracking code to be aware of it. Changing fields does not.