Reputation: 1011
I have a WPF treeview that is loaded from a set of classes hierarchy (strongly-typed-dataset (Entity Framework).) I am looking for the correct way to cast these nodes back as one of these objects.
At the moment I have to write code for each class within my hierarchy (This is an example of how I am deleting an object):
if (MainTree.SelectedItem is tblProject)
{
var s = (tblProject)MainTree.SelectedItem;
_context.tblProjects.Remove(s);
}
if (MainTree.SelectedItem is tblLine)
{
var s = (tblLine)MainTree.SelectedItem;
_context.tblLines.Remove(s);
}
if (MainTree.SelectedItem is tblDevice)
{
var s = (tblDevice)MainTree.SelectedItem;
_context.tblDevices.Remove(s);
}
I would like to know how I could reduce this code, and make it more flexible, so that I do not have to add code for each class that I might add in the future.
Upvotes: 1
Views: 51
Reputation: 3651
In case of EF you can use _context.Set(MainTree.SelectedItem.GetType()).Remove(MainTree.SelectedItem)
In general I would recomend to take a look into Data Binding and MVVM patttern to avoid the similar situations
Upvotes: 1