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 m开发者_运维问答y 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();
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.
精彩评论