views:

105

answers:

1

Using MVVM and EF...I have a datagrid binding to a View Model (using ObservableCollection). The view model has a save command which simply calls the SaveChanges command of the Data Context. However, when a user adds a new row to the datagrid, the new entity is detached. Is there any easy way to automatically attach it when it gets created. Currently, I'm having to do this in the Save command of my View Model and it seems a bit clunky:

        foreach (var dataItem in _DataList)  // where _DataList is the ObservableCollection
        {
            if (dataItem.EntityState == EntityState.Detached)
            {
                _DataContext.AddToTestTables(dataItem);
            }
        }
        _DataContext.SaveChanges();
A: 

Hi,

In this case the solution should be to "observe" your ObservableCollection for any new additions and attach new entities once they are added to the collection.

And Matt Casto is right, you should not have a Save method in your ViewModel, that should be in your Model or ModelRepository depending on the pattern you are using for Data Access Layer.

decyclone
Not sure what you mean by "observe"?
AKoran
Register to the CollectionChanged event. It is raised whenever the number of items in the collection changes.
decyclone