Question

I have a self-referencing table structure working fine with EF, which I use to render a tree view. The EF entity looks like the following and I eagerly load the total structure.

class ListItem
{
  int Id;
  string Text;
  ListItem ParentItem;
  IList<ListItem> ChildItems;
}

Then I added the functionality on the UI to add new child nodes to any node and rearranging the nodes using jQuery. The updated structure is stored in the session using the same entity.

When I want to save it back using EF, I ran into problems as I have it inside another entity like the following, and I am saving(updating) this MainEntity whenever I want to update the tree.

class MainEntity
{
  ..
  ..
  IList<ListItem> Tree;
}

How can I update this Tree property using the values from my session and tell EF to save it? How can I change the parents and children of that structure to match the new structure?

I was thinking of using command pattern to record every action of the UI and replay them later on the EF entity on save. But that looks like an overkill :(

Was it helpful?

Solution

After days of trying out different things in vain I finally implemented command pattern and got it working as expected.

I implemented the following command interface for Add, Update, Delete and Reorder UI actions and stuff them in a collection which resides in the session.

public interface ITreeCommand
{
    void Execute(ICollection<ListItem> finalList, MainEntity source, ModelContainer db, ICollection<Guid> deletedIds);
}

Then on save, I execute these commands in order passing necessary parameters. I had to call db.SaveChanges() inside every execute method implementation. I had to keep the deleted node ids separately because I can skip any unnecessary additions, updates or reordering by checking against this list before executing.

Hope this helps someone someday.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top