How to synchronize an Observablecollection and DBContext?

Use 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();
});
}
));
}
 }</plant>

In collections like observablecollection to submit changes to the DBContext?
June 14th 19 at 20:11
1 answer
June 14th 19 at 20:13
Plants = new ObservableCollection<plant>(_dataContext.Plants);
Plants.CollectionChanged += PlantsOnCollectionChanged;

 private void PlantsOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs args)
{
_dataContext.Plants.AddRange(args.NewItems.Cast<plant>().ToArray());
}</plant></plant>
how to do Update? - Abner commented on June 14th 19 at 20:16
The easiest way is to run NewItems in a loop and try to find each object.
foreach(var entity in args.NewItems.Cast<plant>())
{
var plant = _dataContext.Plants.FirstOrDefault(p => p.Id = entity.Id);
if (plant != null)
{
_dataContext.Set<plant>().Attach(entity);
 _dataContext.Entry(entity).State = EntityState.Modified;
}
else
_dataContext.Set<plant>().Add(entity);
}</plant></plant></plant>

And then call SaveChanges() - willow_Reichert31 commented on June 14th 19 at 20:19

Find more questions by tags .NETMVVMWPF