Saving only fields that have changed in Entity Framework 4 - c#

I have a Windows Form with some textboxes and a Save button. When the form loads the textboxes are populated with data from an entity in my model. When the user clicks on the save button the values in each textbox are written back to the entity and then SaveChanges is called to commit the data to the database.
What I'd like to know is what is the best way to check if the form contains changes? If it doesn't contain changes then I needn't call SaveChanges and I can save writing the record back to the database. If it does contain changes and the user hasn't clicked on the Save button I want to get the user's confirmation that the changes don't need to be saved.
I thought maybe I could just update the entity's fields and then check its State property before calling SaveChanges but this fails as updating any field, even with an identical value, causes the entity to be marked as modified.
So, my question is, what is the best way to check that changes have actually been made to the form before calling SaveChanges?
Thanks,
Matt

You can check the entity state. Just save the data from the textboxes to the entity ans see if the EntityState is EntityState.Unchanged.
Details here: http://msdn.microsoft.com/en-us/library/system.data.entitystate.aspx

Actually updating the field even with the same value as the previous one counts as a modified entity and in most cases this is the correct business rule.
What you could do is keep a copy of the original object that was used to fill the form fields and compare it with the current one using an equality comparer. It's not pretty but it gets the job done in particular cases where you cannot count on the object state manager's opinion of modified.

Related

Defer updating element that is bound to a list

please I need help with the following scenario.
I have a binding list that has entity objects. I am passing the current entity object to a save form that is used to update the entity object passed as a parameter. This save form reads the properties of the entity object class and display controls accordingly. Each of these controls is bound to a property of the entity object. Whenever I change a control value, the corresponding entity property will be updated which will update the entity object in the entity list.
What I need is to apply the changes on the entity object in my save form only after an update button is clicked.
One way around is to make a copy of the entity object before passing it to the save form. But making a deep copy of an object is costly as far as I know.
Create a new class that will resemble the entity and will act as a buffer for the properties on the update form. When the user click's update read all the properties from the buffer class and pass them to the entity and then save it to DB.

How to avoid update when form entries are not changed

Presently In my application , on click of grid row , i fill the control of the page with the grid row entries. I have a UPDATE button to save the changes . But even if the don't modify any control values and click on Update button , updation will be done with same values. that triggers a entry to log table .
How can I make the form to call the update only when the values of the controls are different than what is being loaded to them when i click grid.
UPDATE :
Application is not using any pattern like MVVM . the structure what is being followed is very slimier to win forms except the UI . For db interaction ADO.net . It was built already when i joined to this project & even I am new to wpf.
Can anyone help me out ?
I think that you need to do some change tracking on the Entities displayed in the grid. Whenever an Update is executed you check the state of the entities and only update those entities where it's needed. Basically you need to intercept at the level of Property Setters to keep track of changes in the entity. think about:
Using a base class that has some functionality for keeping track of the state of an entity. Very simple: a Boolean hasChanged or more "complex" an Enum with Added, Modified and Deleted or something.
Derive other entities from this base class
Work with public properties and private backing fields to intercept property modifications
When property modifications are executed store the information in a Boolean or Enum in the base class
When the update is initiated by the user loop through the entities presented in the Grid and pick those that have changes and send them to the database.
Some helpfull theory about this might be:
Change tracking on businees objects
Using Properties C# programming guide
ADO.NET Self Tracking Entities
I don't know from your question how tightly the coupling is between the user interface and the database (ADO.NET DataTables or so...). The idea presented above requires some "decoupling" of things. But, is a good basis for further functionalities in your application and can give you some ease of work, clear framework, improved maintenance and might increase performance.
I believe the easiest way to do this is to add a handler to controls, that are used to get user input, that will set some boolean property, e.d. RowWasEdited, to true. Then check this property on UPDATE button click event, do neccessary actions, and set it to false.
But I'm sure that there is something more elegant than this.

EF4.1 Combobox is databound to navigation properties of an entity, how to save the entity new navigation

Ok, I have a couple of DataBindingSources pointing to context.[DbSet name].Local.ToBindingList()
there's a datagridview bound to such bindingsource, I have 2 columns set to 2 more databindingsources, thus when changing the values using the comboboxes the parent entity's navigation property changes. So far, so good, now when checking the State by:
if(context.Entry(databindingsource.Current).State == EntityState.Modified)
context.SaveChanges();
the State is not Modified but in fact Unchanged, I understand that was intended, and it's not a bug. What I do not understand is how am I suppose to save the changed Navigation property. What is the proper way to go about it? Am I suppose to catch OnChange event from the combobox check the content and set the entity to Modified manually? isn't there a more elegant way?
notes:
lazyloading is off
all entities are loaded prior binding everything to datagridview, comboboxes, and textboxes to their relative databindingsources
all changes are saved when DataBindingSource.CurrentItemChanged event fires
navigation properties are set to already retrieved entities, /ie entities with Unchanged state/
I'd like to post the code, but it's quite a mess, I believe explaining the problem should suffice. but if not I'm more than willing.
EDIT: the model is generated, DataBase first, database did not include any FK's so all associations are made after the entity generation

Pattern for GridView binded to ObjectDataSource - late save

I have a GridView which I am binding to my service layer.
I want to be able to allow the user to edit the grid, but I do not want to save the grid as the user is clicking update on each row. I would like to update all of the edited/added/deleted rows when the 'save' button for my entire form is submitted.
I have my service layer configured, and the GridView calls update on a per row edit basis, however I want that to happen all at the end when clicking save.
How can I maintain my ObjectData sources references to update, insert, delete but instead of on a per row basis be able to call a save on everything all at once?
Thanks!
If you're using an object data source, then the behavior of the object bound to the object data source is up to you; it doesn't have to save to the database right away. If you want, you can build the database commands you want to execute, then cache them somewhere until the save button is clicked.
Object data source objects should be static or stateless, so you can't cache there. However, this sounds like a reasonable use of Session cache.
Here is a tutorial on asp.net/learn for wrapping updates in a transaction:
http://www.asp.net/Learn/Data-Access/tutorial-63-cs.aspx
The example uses GridView and ObjectDataSource.
This may or may not be useful with subsonic, but it may help others with a similar problem.

How do you clear changes in LinqToSql?

I have a combobox in my WPF app that is databound to my list of objects in my View Model. When the user makes changes to the selected object and then selects another item before saving, I need to clear the changes made.
I thought I could use dataContext.GetChangeSet().Updates.Clear() but for some reason the collection is read-only.
I've also tried to use dataContext.Refresh but this doesn't work either as the object doesn't exist in the database, I created it manually from an SP.
Please help. thanks.
As well as using Marc's approach using DeleteOnSubmit (or DeleteAllOnSubmit) to remove the inserts, the following will actually undo any updates aswell:
// clears any updates.
ChangeSet changes = dataContext.GetChangeSet();
dataContext.Refresh(RefreshMode.OverwriteCurrentValues, changes.Updates);
Your best bet is probably to re-query into a separate data-context. You can negate an insert (from the change-set) by using DeleteOnSubmit (and the reverse), but I'd rather not, myself.

Categories