EF and WPF
I had a question today which allow me to do my first WPF poject. 
The guy told me that he has a master detail scenario with two windows: one to edit masters and one to edit details. In details, he wants to choose the master with a combo.
He wants that when he adds one master, the combo adds it also without having to rebind it and without having to save the context.
How to do this?
I developp a class for this:
public class ContextEntitiesLoaded<T> : IEnumerable<T>, INotifyCollectionChanged
{
private ObjectContext _context;
private EntityState _states = EntityState.Added | EntityState.Modified | EntityState.Unchanged;
public ContextEntitiesLoaded(ObjectContext context)
{
_context = context;
_context.ObjectStateManager.ObjectStateManagerChanged += (sender, e) =>
{
if (e.Element is T)
switch (e.Action)
{
case CollectionChangeAction.Add:
case CollectionChangeAction.Remove:
if (e.Element is T)
OnNotifyCollectionChanged();
break;
}
};
}
public EntityState States
{
get { return _states; }
set { _states = value; }
}
public Func<T, object> SortExpression { get; set; }
protected virtual void OnNotifyCollectionChanged()
{
if (CollectionChanged != null)
CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
#region IEnumerable<T> Members
public IEnumerator<T> GetEnumerator()
{
var q = _context.ObjectStateManager.GetObjectStateEntries(States).Select(se => se.Entity).OfType<T>();
if (SortExpression != null)
q = q.OrderBy(SortExpression);
return q.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
#region INotifyCollectionChanged Members
public event NotifyCollectionChangedEventHandler CollectionChanged;
#endregion
}
Then I need to get all the classes in the context and to bind them on the combo:
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
ObjectDataProvider odp = this.FindResource("maSource") as ObjectDataProvider;
if (odp != null)
{
foreach (var c in NorthwindEntities.Instance.Categories); // to load the categories on the context
odp.ObjectInstance = new ContextEntitiesLoaded<Category>(NorthwindEntities.Instance) { SortExpression = c => c.CategoryName };
}
}
[...]
}