I have an ObservableCollection in the ViewModel and I initialize it in the following way:
public ViewModel()
{
List<T> list = null;
using (var context = new DbContext())
{
list = context.Set<T>().ToList();
}
Items = new ObservableCollection<T>(list);
}
And every time I add an item to the context, I add it to the collection too.
public void Add<T>(T obj)
{
using (var context = new DbContext())
{
context.Set<T>().Add(obj);
context.SaveChanges();
}
Items.Add(obj);
}
And when to remove an item from the context, I remove it from the ObservableCollection as well.
There is yet an alternative and I can initialize the ObservableCollection again after the items are added to or removed from the context:
public void Add<T>(T obj)
{
List<T> list = null;
using (var context = new DbContext())
{
context.Set<T>().Add(obj);
context.SaveChanges();
list = context.Set<T>().ToList();
}
Items = new ObservableCollection<T>(list);
}
Now I need to know whether which way is better in case of performance and memory management?