P
P
proger_brut2017-10-04 11:25:07
.NET
proger_brut, 2017-10-04 11:25:07

How to synchronize Observablecollection and DBContext?

I am using MVVM.

ViewModel:
public PlantGridViewModel(IUIVisualizerService uiVisualizerService)
        {
            _uiVisualizerService = uiVisualizerService;
            _dataContext = new GreeptContext();
            Plants = new ObservableCollection<Plant>(_dataContext.Plants);
        }

        public Command AddCommand
        {
            get {
                return _addCommand ?? (_addCommand = new Command(
                    () =>
                        {
                            var viewModel = new PlantViewModel(new Plant());
                            _uiVisualizerService.ShowDialog(viewModel, (sender, e)=>
                            {
                                Plants.Add(viewModel.PlantObject);
                                ???? _dataContext.SaveChanges();
                            });
                        }
                    ));
            }
        }

When changes are made to observablecollections, how to send changes to DBContext?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxmyd, 2017-10-04
@Maxmyd

Plants = new ObservableCollection<Plant>(_dataContext.Plants);
Plants.CollectionChanged += PlantsOnCollectionChanged;

 private void PlantsOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs args)
{
            _dataContext.Plants.AddRange(args.NewItems.Cast<Plant>().ToArray());
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question