I'm using an MVVM structure with EF 6.0 as my data source and a Datagrid as my user control.
I have:
- Viewmodels: a base that implements INotifyPropertChanged, a main viewmodel that holds other viewmodels and a "concrete" viewmodel where data is displayed from.
- Commands: I have an ICommand class and use that in my viewmodel.
In short it so far correctly displays data in a datagrid. Now I want to perform CRUD operations. However when I make changes to the datagrid and then hit my save button (which is bound to an ICommand property) none of the changes propagate back to the entity.
Here is my viewmodel:
class SymbolWeightsViewModel : ViewModelBase
{
BenchMarkEntities _context = new BenchMarkEntities();
RelayCommand _updateCommand;
public ObservableCollection<Weight> Weights
{
get;
private set;
}
public BenchMarkEntities Context
{
get { return _context; }
}
public SymbolWeightsViewModel()
{
_context.Weights.Load();
this.Weights = _context.Weights.Local;
}
~SymbolWeightsViewModel()
{
_context.Dispose();
}
public ICommand UpdateCommand
{
get
{
if (_updateCommand == null)
{
_updateCommand = new RelayCommand(param => this.UpdateCommandExecute(),
param => this.UpdateCommandCanExecute);
}
return _updateCommand;
}
}
void UpdateCommandExecute()
{
using (_context = new BenchMarkEntities())
{
_context.SaveChanges();
}
}
bool UpdateCommandCanExecute
{
get {return true;}
}
My opinion is BenchmarkEntities object and Datagrid are not seeing each other. Why I'm not sure but somewhere that binding is failing. Do I need to reinstantiate BenchmarkEntities to perform an update?
And my View: <StackPanel> <DataGrid ItemsSource="{Binding Weights, Mode=TwoWay, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}" AutoGenerateColumns="True"> </DataGrid> <Button Name="SaveChanges" Height="32" Command="{Binding UpdateCommand}"> </Button> </StackPanel>
View related: I think binding the entire Weight object with the DataGrid is probably not going to work. I need to create and bind to individual columns. Is this true or can you perform updates on a part of an entity via a datagrid?
Really appreciate any help or direction.
Thanks
You create a new Context and then SaveChanges on the new Context which has no pending changes:
void UpdateCommandExecute()
{
using (_context = new BenchMarkEntities())
{
_context.SaveChanges();
}
}